Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array of data to jQuery function

Here's the story... I have a jQuery function that does something, this function is referenced very regularly. One of the input parameters is an array, this array data is hard coded and thus I want to pass the data like this: (this is how I would do it using PHP)

myFunction(Array("url"=>"abc.com","example"=>"hello_world"));

Instead of

$arr=Array("url"=>"abc.com","example"=>"hello_world");
myFunction($arr);

So how do I achieve this with my jQuery function, I want this to be a one liner if possible.

Edit

Maybe my example was a bit misleading, take a look at the array indexes again. The array I am sending is an associative array.

In short I do not want any variables before my function, I want the array to be hardcoded directly in the function parameter as suggested in the first example I gave.

:-)

like image 629
Ben Everard Avatar asked Mar 22 '10 10:03

Ben Everard


2 Answers

I reread your edited question, and your answer is in the javascript object, much like dictionaries or hashes in other languages:

    { first_key: '1', second_key: '2', third_key: '3' };

And for your callback, just pass it in as a literal declared on the spot:

    myFunction({ first_key: '1', second_key: '2', third_key: '3'});
like image 86
ground5hark Avatar answered Oct 01 '22 21:10

ground5hark


Here is example if this is what you mean:

    var arr = [ "one", "two", "three", "four", "five" ];

    jQuery.each(arr, function() {
          $("#" + this).text("Mine is " + this + ".");
           return (this != "three"); // will stop running after "three"
       });

//Source http://api.jquery.com/jQuery.each/
like image 22
ant Avatar answered Oct 01 '22 19:10

ant