HTML and CSS Reference
In-Depth Information
Of course, we did not need to declare the function first, we could have written the same
functionality as follows:
> a.filter(function(i) {return i % 2 == 0})
[2, 4, 6, 8, 10]
The function passed to the filter method in this case is an anonymous function (i.e. a func-
tion without a name). This function only exists for the duration of the filter call, and cannot
be reused.
Let's now imagine a more complex example. Suppose we want to take an array, multiply
each element by itself, and then return the result if it is even.
JavaScript arrays also have a method called map . Like filter , map passes each member of
the array to a function, and then returns a new array with the result of these function calls.
//
It is important to note that these methods are not altering the original array;
they are creating a new array with the appropriate entries. This is an important
paradigm, since it means the method call will not impact any other code that has
a reference to the original array.
In order to multiply each member by itself, we could execute:
> a.map(function(i) {return i*i})
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In order to return the even numbers amongst these, we could therefore perform the filter
method on the array returned by the map call:
a.map(function(i) {return i*i}).filter(function(i) {return i % 2 == 0})
[4, 16, 36, 64, 100]
Finally, let's imagine that we want to sum the values in the final array. Arrays.prototype
supports a reduce method for this. This method is slightly more complex than map and
 
Search WWH ::




Custom Search