JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

11.4.4 Array Comprehensions

11.4.4 Array Comprehensions

An array comprehension is another feature that JavaScript 1.7 borrowed from Python. It is a technique for initializing the elements of an array from or based on the elements of another array or iterable object. The syntax of array comprehensions is based on the mathematical notation for defining the elements of a set, which means that expressions and clauses are in different places than JavaScript programmers would expect them to be. Be assured, however, that it doesn’t take long to get used to the unusual syntax and appreciate the power of array comprehensions.

Here’s an array comprehension that uses the range() function developed above to initialize an array to contain the even square numbers up to 100:

let evensquares = [x*x for (x in range(0,10)) if (x % 2 === 0)]

It is roughly equivalent to the following five lines:

let evensquares = []; for(x in range(0,10)) { if (x % 2 === 0)

evensquares.push(x*x); }

In general, an array comprehension looks like this:

[ expression for ( variable in object ) if ( condition ) ]

Notice that there are three main parts within the square brackets:

Here are some more concrete examples to clarify the syntax:

data = [2,3,4, -5]; // An array of numbers squares = [x*x for each (x in data)]; // Square each one: [4,9,16,25] // Now take the square root of each non-negative element roots = [Math.sqrt(x) for each (x in data) if (x >= 0)]

// Now we'll create arrays of property names of an object

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1