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

the third is 4, and so on. When myNumbers() completes without calling yield (after the final loop<br />

iteration), calling next() throws a StopIteration error. So to output all numbers in the generator, a<br />

while loop is wrapped in a try - catch statement to prevent the error from stopping code execution.<br />

If a generator is no longer needed, it ’ s best to call the close() method. Doing so ensures that the rest of<br />

the original function is executed, including any finally blocks related to try - catch statements.<br />

Generators are useful when a sequence of values need to be produced and each subsequent value is<br />

somehow related to the previous one.<br />

Iterators<br />

An iterator is an object that iterates over a sequence of values and returns them one at a time. When you<br />

use a for loop or a for - in loop, you ’ re typically iterating over values and processing them one at a<br />

time. Iterators provide the ability to do the same without using a loop. JavaScript 1.7 supports iterators<br />

for all types of objects.<br />

To create an iterator for an object, use the Iterator constructor and pass in the object whose values<br />

should be iterated over. The next() method is used to retrieve the next value in the sequence. By<br />

default, this method returns an array whose first item is the index of the value (for arrays) or the name of<br />

the property (for objects) and whose second item is the value. When no further values are available,<br />

calling next() throws a StopIteration error. Here is an example:<br />

var person = {<br />

name: “Nicholas”,<br />

age: 29<br />

};<br />

var iterator = new Iterator(person);<br />

try {<br />

while(true){<br />

let value = iterator.next();<br />

document.write(value.join(“:”) + “ < br / > ”);<br />

}<br />

} catch(ex){<br />

//intentionally blank<br />

}<br />

This code creates an iterator for the person object. The first time next() is called, the array [ “ name ” ,<br />

“ Nicholas “ ] is returned, and the second call returns [ “ age ” , 29] . The output from this code is as<br />

follows:<br />

name:Nicholas<br />

age:29<br />

When an iterator is created for a non - array object, the properties are returned in the same order as they<br />

would be in a for - in loop. This also means that only instance properties are returned and the order<br />

in which the properties are returned varies upon implementation.<br />

711

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

Saved successfully!

Ooh no, something went wrong!