HTML and CSS Reference
In-Depth Information
In this code, assume that the evenNumber array is created with a list of what you expected
to be all even numbers. To validate this, you can use the every method.
The every method takes two parameters:
The name of the function that should be processed for each element
An optional reference to the array object
The evenNumberCheck function called for each item in the array returns true or false for
each item, depending on whether it meets the desired criteria. In this example, the value
is tested to ensure that it's an even number. If it is, the function returns true ; otherwise, it
returns false . As soon as the every method gets the first false result for any item in the array,
it exits and returns false . Otherwise, if all elements in the array return true , the every method
returns true . In the preceding code sample, an if statement was added to evaluate the return
value of the every method and take an appropriate action. In this example, the evenNumber-
Check function returns false on the sixth item in the array, because 9 is an odd number, so the
test for even fails.
Using the some method
The some method works very much like the every method. The difference is that some checks
only whether any item in the array meets the criteria. In this case, the some method returns
true if the called function returns true for any single element. If all elements in the array re-
turn false , the some method returns false . By this definition, you can use some to achieve the
exact opposite of the every method when the some method returns false . The following code
is updated from the previous example so that it uses the some method:
var evenNumbers = new Array(0, 2, 4, 6, 8, 9, 10, 12);
var allEven = evenNumbers.some(evenNumberCheck, evenNumbers);
if (allEven) {
} else {
function evenNumberCheck(value, index, array) {
return (value % 2) == 0;
With the code updated to use the some method, the return result isn't true , because some
of the values in the array are even numbers. Had this result returned false , you would know
that all the elements in the array were odd numbers.
Search WWH ::

Custom Search