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 />

var evens = [i for each (i in numbers) if (i % 2 == 0)];<br />

//multiply every value by 2<br />

var doubled = [i*2 for each (i in numbers)];<br />

//multiply every odd number by 3<br />

var tripledOdds = [i*3 for each (i in numbers) if (i % 2 > 0)];<br />

All of the array comprehensions in this code use i as a variable to iterate over all values in numbers .<br />

Some of them use conditions to filter the results of the array. Essentially, if the condition evaluates to<br />

true, the value is added to the array. The syntax is a little different from traditional JavaScript but is<br />

more succinct than writing your own for loop to accomplish the same task. Firefox (version 2 and later)<br />

is the only browser to implement this feature, and it requires the type attribute of the < script > element<br />

to be “ application/<strong>javascript</strong>;version=1.7 ” to enable it.<br />

The values portion of an array comprehension can also be a generator or an iterator.<br />

Destructuring Assignments<br />

It ’ s quite common to have a group of values from which you want to extract one or more into individual<br />

variables. Consider the value returned from an iterator ’ s next() method, which is an array containing<br />

the property name and value. In order to store each in its own variable, it would require two statements,<br />

as in this example:<br />

var nextValue = [“color”, “red”];<br />

var name = nextValue[0];<br />

var value = nextValue[1];<br />

A destructuring assignment allows you to assign both array items into variables using a single statement<br />

such as this:<br />

var [name, value] = [“color”, “red”];<br />

alert(name); //”color”<br />

alert(value); //”red”<br />

In traditional JavaScript syntax, an array literal cannot be on the left side of an assignment. Destructuring<br />

assignment introduces this syntax to indicate that the variables contained in the array to the left of the<br />

equal sign should be assigned the values contained in the array to the right of the equal sign. The result<br />

is that name is filled with “ color ” , and value is filled with “ red ” .<br />

If you don ’ t want all of the values, you can provide variables just for the ones you want, as in this<br />

example:<br />

var [, value] = [“color”, “red”];<br />

alert(value); //”red”<br />

Here, only the variable value is assigned, and it receives the value “ red ” .<br />

713

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

Saved successfully!

Ooh no, something went wrong!