Aug 07

JQuery: utility functions IV – interacting through arrays

Posted in JQuery      Comments Off on 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.