Web Development with jQuery®

(Elliott) #1

Iteration of Arrays and Objects


This chapter discusses the methods jQuery provides to help you work with looking at the
contents of arrays and objects. Historically, working with arrays or objects in JavaScript often
required you to come up with your own helper methods and to deal with writing tedious
redundant code every time you wanted to enumerate over the contents of an array—for exam-
ple, creating a counter variable each time you wanted to enumerate over the content of
an array.

As you saw in Chapter 4, “Manipulating Content and Attributes,” jQuery provides a rich,
robust, and helpful API for various tasks associated with manipulating the content in a docu-
ment. In this chapter, you see that jQuery also does not leave much to be desired in what it
offers for dealing with arrays or objects.

Enumerating Arrays


In this section, you learn how to approach the task of enumerating or iterating over an array
of values using jQuery’s $.each() method, by calling each() via jQuery and each() directly.
The term enumerate means to examine items one by one, and the term iterate means to do
something repeatedly. These terms are often used interchangeably to describe the process of
looking at the contents of an array, list, or object. Up to now, when looking at each individual
value contained within an array, you might be used to dealing with a loop that looks some-
thing like this, which is the way it was been done in JavaScript before frameworks such as
jQuery became ubiquitous:

var divs = document.getElementsByTagName('div');

for (var counter = 0; counter < divs.length; counter++)
{
// Do something with each item
console.log(divs[counter].innerHTML);
}

5


http://www.it-ebooks.info

Free download pdf