04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 22: The Evolution of JavaScript<br />

Of these methods, the two most similar are every() and some() , which each query the array for items<br />

matching some criteria. For every() , the passed - in function must return true for every item in order<br />

for the method to return true ; otherwise, it returns false . The some() method, on the other hand,<br />

returns true if even one of the items causes the passed - in function to return true . Here is an example:<br />

var numbers = [1,2,3,4,5,4,3,2,1];<br />

var everyResult = numbers.every(function(item, index, array){<br />

return (item > 2);<br />

});<br />

alert(everyResult);<br />

//false<br />

var someResult = numbers.some(function(item, index, array){<br />

return (item > 2);<br />

});<br />

alert(someResult);<br />

//true<br />

This code calls both every() and some() with a function that returns true if the given item is greater<br />

than 2. For every() , the result is false because only some of the items fit the criteria. For some() , the<br />

result is true because at least one of the items is greater than 2.<br />

The next method is filter() , which uses the given function to determine if an item should be included<br />

in the array that it returns. For example, to return an array of all numbers greater than 2, the following<br />

code can be used:<br />

var numbers = [1,2,3,4,5,4,3,2,1];<br />

var filterResult = numbers.filter(function(item, index, array){<br />

return (item > 2);<br />

});<br />

alert(filterResult); //[3,4,5,4,3]<br />

Here, an array containing the values 3, 4, 5, 4, and 3 is created and returned by the call to<br />

filter() because the passed - in function returns true for each of those items. This method is very<br />

helpful when querying an array for all items matching some criteria.<br />

The map() method also returns an array, but the contents of the array are equal to the return value of the<br />

passed - in function for each item. For example, you can multiply every number in an array by two and<br />

are returned an array of those numbers, as shown here:<br />

var numbers = [1,2,3,4,5,4,3,2,1];<br />

var mapResult = numbers.map(function(item, index, array){<br />

return item * 2;<br />

});<br />

alert(mapResult); //[2,4,6,8,10,8,6,4,2]<br />

707

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!