JQuery: utility functions IV – interacting through arrays

Published Fri, Aug 7 2009 15:07

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.

Filed under:

Comments

# 9eFish said on Sunday, August 09, 2009 8:46 AM

9efish.感谢你的文章 - Trackback from 9eFish

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover