Iteration
Mozilla’s JavaScript extensions introduce new iteration
techniques, including the for each
loop and Python-style iterators and generators. They are detailed in
the subsections below.
The for/each Loop
The for/each loop is a new
looping statement standardized by E4X. E4X (ECMAScript for XML) is a
language extension that allows XML tags to appear literally in
JavaScript programs and adds syntax and API for operating on XML
data. E4X has not been widely implemented in web browsers, but it is
supported by Mozilla’s JavaScript 1.6 (released in Firefox 1.5). In
this section, we’ll cover only the for/each loop and its use with non-XML
objects. See E4X: ECMAScript for XML for details on the rest of
E4X.
The for each loop is much
like the for/in loop. Instead of
iterating through the properties of an object, however, it iterates
through the values of those properties:
leto={one:1,two:2,three:3}for(letpino)console.log(p);// for/in: prints 'one', 'two', 'three'foreach(letvino)console.log(v);// for/each: prints 1, 2, 3
When used with an array, the for/each loop iterates through the
elements (rather than the indexes) of the loop. It typically
enumerates them in numerical order, but this is not actually
standardized or required:
a=['one','two','three'];for(letpina)console.log(p);// Prints array indexes 0, 1, 2foreach(letvina)console.log(v);// Prints array elts 'one', 'two', 'three'
Note that the for/each loop does not limit itself to the array elements ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access