Java Reference
In-Depth Information
figure 5-2
This code can be rewritten to use the
forEach()
method. As its name implies, it does something
for
each
element in the array. All you need to do is write a function to double a given value and output
the result in an
alert
box, like this:
var numbers = [ 1, 2, 3, 4, 5 ];
function doubleAndAlert(value, index, array) {
var result = value * 2;
alert(result);
}
numbers.forEach(doubleAndAlert);
Notice that the
doubleAndAlert()
function doesn't return a value like the testing methods. It
cannot return a value; its only purpose is to perform an operation on every element in the array.
This is useful in many cases, but you'll want to use the
map()
method when you need to store the
results of the function.
The premise of the
map()
method is similar to that of
forEach()
. It executes a given function
on every element in an array, but it also returns a new array that contains the results of the
function.
Let's modify the previous example and write a new function called
doubleAndReturn()
. It will
still double each element in the array, but it will return the doubled value instead of alerting