Java Reference
In-Depth Information
The map() method is very similar to the forEach() method. It also iterates over an ar-
ray and takes a callback function as a parameter that is invoked on each item in the array.
This is often used to process data returned from databases in array form, such as adding
HTML tags to plain text. The difference is that it returns a new array that replaces each
value with the return value of the callback function. For example, we can square every
number in an array using the square function we wrote previously as a callback to the
map() method:
[1,2,3].map( square )
<< [1, 4, 9]
An anonymous function can also be used as a callback. This example will write all items in
the array in uppercase and place them inside paragraph tags:
["red","green","blue"].map( function(color) { return "<p>"
+ color.
toUpperCase() + "</p>"; } );
<< ["<p>RED</p>", "<p>GREEN</p>", "<p>BLUE</p>"]
Notice in this example the anonymous function takes a parameter, color , which refers to
the item in the array. This callback can also take two more parameters ― the second para-
meter refers to the index number in the array and the third refers to the array itself. All three
parameters can be seen in the next example:
["red","green","blue"].map( function(color, index, array)
{ return
index + ": " + color + " (length " + array.length + ")";
} );
<< ["0: red (length 3)", "1: green (length 3)", "2: blue
(length 3)
Search WWH ::

Custom Search