HTML and CSS Reference
In-Depth Information
For example, the following forEach() method applies the sumArray() function for each
item in the x array:
var x = [2, 5, 7, 12];
var sum = 0;
x.forEach(sumArray);
function sumArray(value) {
sum += value;
}
Note that the sumArray() function has a single parameter; and because the value parameter
is the first (and only) parameter listed, the function acts upon the value of each array item.
The result of running the forEach() method is that the value of the sum variable will
be set to the sum of the values in the x array, which in this case is equal to 26.
The following forEach() method calls the stepUp() function to increase each value
in the x array by 1:
var x = [4, 7, 11];
x.forEach(stepUp);
function stepUp(value, i, arr) {
arr[i] = value + 1;
}
Notice that in this case, the stepUp() function has three parameters, with the second
parameter ( i ) representing the array index and the third parameter ( arr ) representing the
array itself.
After running this code, the x array would contain the values [5, 8, 12] because each
item from the original array has been increased by 1.
Mapping an Array
The map() method performs a similar action to the forEach() method except that the
function it calls returns a value that can be used to map the contents of an existing array
into a new array. The following code demonstrates how to use the map() method to cre-
ate a new array in which each item is equal to twice the value of the corresponding item
in the original array:
var x = [3, 8, 12];
var y = x.map(DoubleIt);
function DoubleIt(value) {
return 2*value;
}
After running this code, the y array contains the values [6, 16, 24]. Note that the map()
method does not affect the contents or structure of the original array, and the new array
will have the same number of array items as the original. If the original array is sparse
with several missing indices, the mapped array will have the same sparseness.
Filtering an Array
Often when working with arrays, you'll want to extract array items that match some
specified condition. For example, in an array of test scores, you might want to extract
only those test scores with a value of 70 or below. The filter() method
array .filter( function )
Search WWH ::




Custom Search