jQuery in Action
170
CHAPTER 6
jQuery utility functions
This unified syntax can be used to iterate over either arrays or objects using the
same format. Using this function, we write the previous example as follows:
same format. Using this function, we write the previous example as follows:
var anArray = ['one','two','three'];
$.each(anArray,function(n,value) {
//do something here
});
var anObject = {one:1, two:2, three:3};
$.each(anObject,function(name,value) {
//do something here
});
Although using
$.each()
with an inline function may seem like a six-of-one sce-
nario in choosing syntax, this function makes it easy to write reusable iterator
functions or to factor out the body of a loop into another function for purposes of
code clarity as in the following:
functions or to factor out the body of a loop into another function for purposes of
code clarity as in the following:
$.each(anArray,someComplexFunction);
Note that when iterating over an array, we can break out of the loop by returning
false
from the iterator function. Doing so when iterating over object properties
has no effect.
Sometimes we may iterate over arrays to pick and choose elements to become
part of a new array. Let's see how jQuery makes that easy.
6.3.3 Filtering arrays
Traversing an array to find elements that match certain criteria is a frequent need
of applications that handle lots of data. We might wish to filter through the data
looking for items that fall above or below a particular threshold or, perhaps, that
match a certain pattern. For any filtering operation of this type, jQuery provides
the
of applications that handle lots of data. We might wish to filter through the data
looking for items that fall above or below a particular threshold or, perhaps, that
match a certain pattern. For any filtering operation of this type, jQuery provides
the
$.grep()
utility function.
The name of the
$.grep()
function might lead us to believe that the function
employs the use of regular expressions like its namesake, the
UNIX
grep
com-
mand. But the filtering criteria used by the
$.grep()
utility function isn't a regu-
lar expression; it's a callback function provided by the caller that defines the criteria
to determine if a data value should be included or excluded from the resulting set
of values. Nothing prevents that callback from using regular expressions to
accomplish its task, but the use of regular expressions is not automatic.
to determine if a data value should be included or excluded from the resulting set
of values. Nothing prevents that callback from using regular expressions to
accomplish its task, but the use of regular expressions is not automatic.
The syntax of the function is as follows: