JQuery: utility functions IV – interacting through arrays

In this post, we’re going to look at the each utility function. This function expects two parameters: an object which is going to be enumerated and a callback function reference which is going to be called for each item in the enumerated set. It’s important to understand that this is different from the each jQuery method (which is used for interacting over each element of the wrapped set).

Traditionally, you use indexes for going through all the items in an array. There are also some times where you need to enumerate all the properties of an object. In those cases, you’ll generally use the for in loop. If you want, you can reduce the code needed by using the each method. When you’re using an array, you’ll be writing a function that receives one parameter:

var arr = [1, 2, 3];
$.each(arr, function(val) { alert(val); });

On the other hand, if you’re enumerating properties, then you’ll need (at least) two parameters: one for the property name and another for the value:

var obj = { name: "John", age: 12 };
$.each(obj,function(prop,val) { alert(prop + ":" + val) });

You probably won’t find much value in using the functionality of this method, but  you’ll notice that it does reduce the amount of required typing. Before ending, there’s still time for saying that returning false from the method results in stopping the enumeration of the existing items.

And that’s it. Keep tuned for more on JQuery.


~ by Luis Abreu on August 7, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: