jQuery in Action
Manipulating JavaScript objects and collections
169
6.3.2 Iterating through properties and collections
Oftentimes when we have non-scalar values composed of other components, we'll
need to iterate over the contained items. Whether the container element is a
JavaScript array (containing any number of other JavaScript values, including
other arrays) or instances of JavaScript objects (containing properties), the Java-
Script language gives us means to iterate over them. For arrays, we iterate over
their elements using the
need to iterate over the contained items. Whether the container element is a
JavaScript array (containing any number of other JavaScript values, including
other arrays) or instances of JavaScript objects (containing properties), the Java-
Script language gives us means to iterate over them. For arrays, we iterate over
their elements using the
for
loop; for objects, we iterate over their properties
using the
for-in
loop.
We can code examples of each as follows:
var anArray = ['one','two','three'];
for (var n = 0; n < anArray.length; n++) {
//do something here
}
var anObject = {one:1, two:2, three:3};
for (var p in anObject) {
//do something here
}
Pretty easy stuff, but some might think that the syntax is needlessly wordy and com-
plex--a criticism frequently targeted at the
plex--a criticism frequently targeted at the
for
loop. We know that, for a wrapped
set of
DOM
elements, jQuery defines the
each()
command, allowing us to easily iter-
ate over the elements in the set without the need for messy
for
syntax. For general
arrays and objects, jQuery provides an analogous utility function named
$.each()
.
The same syntax is used whether iterating over the items in an array or the
properties of an object.
Function syntax: $.each
$.each(container,callback)
Iterates over the items in the passed container, invoking the passed callback function for each.
Parameters
container
(Array|Object) An array whose items or an object whose properties are to be
iterated over.
iterated over.
callback
(Function) A function invoked for each element in the container. If the con-
tainer is an array, this callback is invoked for each array item; if it's an
object, the callback is invoked for each object property.
The first parameter to this callback is the index of the array element or the name
of the object property. The second parameter is the item or property value.
The function context (this) of the invocation is also set to the value passed
as the second parameter.
tainer is an array, this callback is invoked for each array item; if it's an
object, the callback is invoked for each object property.
The first parameter to this callback is the index of the array element or the name
of the object property. The second parameter is the item or property value.
The function context (this) of the invocation is also set to the value passed
as the second parameter.
Returns
The container object.
The container object.