Enumerating Arrays (^) ❘ 139
this keyword. The current index and value can be accessed optionally by providing two arguments
to the callback function. Alternatively, you can also call each() directly. Calling each() directly
places the array as the fi rst argument and the callback function as the second argument.
Unfortunately, enumerating objects isn’t as fl exible as enumerating arrays, which is covered in the
next section.
Enumerating Objects
Enumerating objects with jQuery is done by calling each() directly; when each() is called via
jQuery, jQuery gets confused about what it is supposed to do with the object because jQuery
does other things with objects passed to it this way. The following script takes another look at the
example presented in Example 5-1, but this time both of the arrays are rewritten as plain objects,
so you can observe the differences between enumerating an array and enumerating an object. The
same HTML and CSS are used as in Example 5-1; you can access this example in the free download
materials from http://www.wrox.com/go/webdevwithjquery. This example is named Example 5-2.
$(document).ready(
function()
{
var beatles = {
john : 'John Lennon',
paul : 'Paul McCartney',
george : 'George Harrison',
ringo : 'Ringo Starr'
};
var ul = $('ul#beatles');
// each() called via jQuery
$(beatles).each(
function()
{
ul.append('<li>' + this + '</li>');
}
);
var albums = {
1 : 'Please Please Me',
2 : 'With the Beatles',
3 : 'A Hard Day\'s Night',
4 : 'Beatles for Sale',
5 : 'Help!',
6 : 'Rubber Soul',
7 : 'Revolver',
8 : 'Sgt. Pepper\'s Lonely Hearts Club Band',
9 : 'Magical Mystery Tour',
10 : 'The Beatles',
11 : 'Yellow Submarine',
12 : 'Abbey Road',
13 : 'Let It Be'
};