Java Reference
In-Depth Information
The result is true because some of the elements in the array are less than 3 . It's easy to keep these
two methods straight. Just remember the every() method returns true if, and only if, all elements
in the array pass the test in your function; the some() method returns true if, and only if, some of
the elements in the array pass your function's test.
Let's assume you want to retrieve the elements that have a value less than 3 . You already know
some elements meet this criterion, but how do you identify those elements and retrieve them? This is
where the filter() method becomes useful.
The filter() method executes your function on every element in the array, and if your function
returns true for a particular element, that element is added to a new array that the filter()
method returns. Keeping that in mind, look at the following code:
var numbers = [ 1, 2, 3, 4, 5 ];
 
function isLessThan3(value, index, array) {
var returnValue = false;
 
if (value < 3) {
returnValue = true;
}
 
return returnValue;
}
 
if (numbers.some(isLessThan3)) {
var result = numbers.filter(isLessThan3);
alert("These numbers are less than 3: " + result);
}
This code redefines the numbers array and the isLessThan3 function used in previous examples.
The highlighted code determines if any elements in the numbers array contain a value less than 3 ,
and if so, calls the filter() method to place those elements into a new array. The result of this code
is shown in Figure 5-2.
Operating on Elements—The forEach() and map() Methods
The final two methods are the forEach() and map() methods. Unlike the previous iterative methods,
these two methods do not test each element in the array with your function; instead, the function
you write should perform some kind of operation that uses the element in some way. Look at the
following code:
var numbers = [ 1, 2, 3, 4, 5 ];
 
for (var i = 0; i < numbers.length; i++) {
var result = numbers[i] * 2;
alert(result);
}
As a programmer, you'll often see and use this type of code. It defines an array and loops through it
in order to perform some kind of operation on each element. In this case, the value of each element
is doubled, and the result is shown in an alert box to the user.
Search WWH ::




Custom Search