Java Reference
In-Depth Information
Array Iterators
ECMAScript 5 introduced a number of methods for arrays that utilize callbacks to make
them much more flexible.
forEach()
In the last chapter, we saw that a for loop could be used to loop through each value in an
array like so:
var colors = ["Red", "Green", "Blue"]
for( var i = 0, max = colors.length ; i < max ; i++ ) {
console.log("Color at position " + i + " is " +
colors[i]);
}
<< "Color at position 0 is Red"
"Color at position 1 is Green"
"Color at position 2 is Blue"
An alternative is to use the forEach() method. This will loop through the array and in-
voke a callback function using each value as an argument. The callback function takes three
parameters, the first represents the value in the array, the second represents the current in-
dex and the third represent the array that the callback is being called on. The example above
could be written as:
colors.forEach(function(color,index){
console.log("Color at position " + index + " is " +
color);
});
<< "Color at position 0 is Red"
"Color at position 1 is Green"
"Color at position 2 is Blue"
Search WWH ::




Custom Search