Java Reference
In-Depth Information
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 another array the filter() method
returns. Keeping that in mind, look at the following code:
var numbers = new Array(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 defi nes the numbers array and the isLessThan3 function used previously. The new code
determines if any elements in the numbers array contain a value less than 3. If so, the filter()
method is called and returns those elements in a new array. The result of this code can be seen in
Figure 5-2.
Figure 5-2
As you can see, the filter() method in combination with the some() method can be quite useful!
Before moving on, let's revisit the isLessThan3() function. As you have seen, the function works as is
without any modifi cation. However, the function's body can be simplifi ed and made more effi cient. The
following code shows you this simplifi ed version:
function isLessThan3(value, index, array)
{
return (value < 3);
}
Isn't that much easier? JavaScript, like most other languages, returns conditional statements as true or
false, and you can assign the returned value to a variable. In this case, the value returned from the
conditional statement is simply returned to the calling code.
Search WWH ::




Custom Search