HTML and CSS Reference
In-Depth Information
can be used to create such subarrays, where function is a function that returns a Boolean
value of true or false for each item in the array. The array items that result in a value of
true get filtered or passed into a new array. The following code demonstrates how to use
the filter() method to create a subarray of items whose value is less than 70:
var scores = [92, 68, 83, 65, 71, 55];
var lowScores = scores.filter(getLow);
function getLow(value) {
return value < 70;
}
After running this code, the lowScores array would contain the values [68, 65, 55].
In another common use of arrays, you want to examine an array's contents to deter-
mine whether every array item satisfies a specified condition. The every() method
array .every( function )
returns the value true if every item in an array matches the condition specified in
function , and returns false otherwise. Note that the function used by the every()
method must return a Boolean value of true or false . For example, the following code
uses the every() method to test whether every test score exceeds a value of 70:
var scores = [85, 92, 88, 69, 71];
var allPassing = scores.every(passTest);
function passTest(value) {
return value > 70;
}
In this example, the allPassing variable would be false because at least one array item
(69) does not exceed 70. Similarly, the some() method
array .some( function )
returns a value of true or false if some—but not necessarily all—array items match a
condition specified in function .
Altogether, nine new methods for working with arrays were introduced in ECMAScript 5.
Figure 12-18 summarizes the syntax and uses of each method.
Figure 12-18
summary methods for arrays
Method Description
every( function ) Tests whether the condition returned by function holds for all items
in the array ( true ) or at least one counter-example exists ( false )
filter( function ) Creates a new array populated with the elements of the original array
that return a value of true from function
forEach( function ) Applies function to each item within the array
indexOf( value [, start ]) Searches the array, returning the index number of the first element
equal to value , starting from the optional start index
lastIndexOf( value [,
start ])
Searches backward through the array, returning the index number of
the first element equal to value , starting from the optional start index
map( function )
Creates a new array by passing the original array items to function ,
which returns the mapped value of the array items
reduce( function )
Reduces the array by passing the original array items to function ,
keeping only those items that return a value of true
 
Search WWH ::




Custom Search