Ecmascript6-iterators and generators

Source: Internet
Author: User

Iterators and generators

Iterators has been used in many programming languages as a-to-more easily work with collections of data. In ECMAScript 6, JavaScript adds iterators as an important feature of the language. When coupled with the new array methods and new types of collections (such as sets and maps), iterators become even more impor Tant for efficient processing of data.

In other languages, a walker is used to manipulate data collections more easily. In ES6, JS adds the ergodic device as an important feature of the language. When combined with new array methods and new collection types (such as set and map), the Walker becomes more important because of the ability to process data efficiently.

What is iterators?-what is a ergodic device

Iterators is nothing more than objects with a certain interface. That's interface consists of a method called that next() returns a result object. The result object has both properties, value which is the next value, and done , which are a Boolean value that ' s true whe N There is no more values to return. The iterator keeps an internal pointer to a location within a collection of values and, with all call next() to, returns T He next appropriate value.

A walker is just an object that has a specific interface. This interface contains a method called Next () to return the result object. The result object has two properties: the value of Value-next, and the done-boolean value, which indicates that the next time there will be no return value. The Walker has an internal pointer to locate the value of the collection, and each time the next method is called, the next appropriate value is returned.

If the last next() value has been returned, the method returns as and done contains the true value return Value for the iterator. The return value is not considered part of the data set, but rather a final piece of related data or undefined if no Such data exists. (This concept'll become clearer in the generators sections later in this chapter.)

If Next () is called after the last value is returned, the done value returned by this method is True,value contains the return value of the Walker, the return value is not part of the collection, but the last related data or undefined if the data is not defined.

With that understanding, it's fairly easy to create a iterator using ECMAScript 5, for example:

To understand this, it is also easy to create a walker using ES5, for example:

function createiterator (items) {var i = 0;            return {next:function () {var done = (i >= items.length); var value =!done?            items[i++]: undefined;        return {done:done, value:value}; }    };}           var iterator = Createiterator ([1, 2, 3]); Console.log (Iterator.next ());           "{value:1, Done:false}" Console.log (Iterator.next ());           "{value:2, Done:false}" Console.log (Iterator.next ());           "{Value:3, Done:false}" Console.log (Iterator.next ());           "{value:undefined, done:true}"//For all further Callsconsole.log (Iterator.next ()); ' {value:undefined, done:true} ' 

The createIterator() function in this example returns an object with a next() method. Each of the method is called, and the next value in the items array is returned as value . When i was 4, items[i++] returns undefined done true and is, which fulfills the special last case for iterators in ECMAScript 6.

The Createiterator function in this example returns an object that has the next method. Whenever this method is called, the next value in the items array is returned as the Value property. When I equals 4, item[i++] Returns the value of undefined and done to true, conforming to the ergodic characteristics in ES6.

ECMAScript 6 makes use of iterators in a number of places to make dealing with collections of data easier, so have a goo D Basic Understanding allows you to better understand the language as a whole.

It's easier to use a ES6 in many places to handle collection data, so having a good understanding can help you understand the whole language better.

generators-Generator

You might is thinking that iterators the sound interesting but the they look like a bunch of work. Indeed, writing iterators so they adhere to the correct behavior are a bit difficult, which is why ECMAScript 6 provid ES generators. A generator is a special kind of the function that returns an iterator. Generator functions is indicated by inserting a star character ( * ) after the function keyword ( It doesn ' t matter if the star is directly next to function or if there ' s some whitespace between them). The yield keyword is used inside of generators to specify the values of the iterator should return when next () is called. So if you want to return three different values for each successive call to next () , you can do as follows:

You might think that the walker sounds interesting, but they need a lot of work. Indeed, it is a bit difficult to write a walker that ensures that the behavior is correct, which is why ES6 introduced the generators (generator), and a generators is a special function that can return a walker. The generator adds a star character (*) after the function keyword to indicate whether the star character and the function keyword have no effect on the space. The yield keyword is used inside the generator to define what value should be returned when the next method call of the walker is called. So if you want to return three different values each time you call next, you can do something like this:

Generatorfunction *createiterator () {    yield 1;    Yield 2;    Yield 3;} Generators is called like regular functions but return a iteratorlet iterator = Createiterator (); for (Let I of Iterat OR) {    console.log (i);}

This code outputs the following:

The output of this code is as follows:

123

In this example, the createIterator() function was a generator (as indicated by the * before the name) and it's called Like any OT her function. The value returned is a object that adheres to the iterator pattern. Multiple yield statements inside the generator indicate the progression of values that should being returned when is next() CA Lled on the iterator. First, next() should return 1 , then 2 , and then 3 before the iterator is finished.

In this example, the Createiterator function is a generator (a star character preceded by a function name), and its invocation is the same as other functions. The returned value is an object in the form of a walker. Multiple yield declarations inside the generator indicate that these values are returned sequentially when the next method of the Walker is called. The first time next returns 1, then 2 and 3.

Perhaps the most interesting aspect of generator functions are that they stop execution after each yield statement, so executes and then the function doesn ' t execute anything else until the iterator ' s next() method is called. At a point, execution resumes with the next statement after yield 1 , which in this case is yield 2 . This ability to stop execution in the middle of a function are extremely powerful and lends to some interesting uses of Gen Erator functions (discussed later in this chapter).

Perhaps the most interesting aspect of the generator is that after each yield declaration executes, the generator function stops executing, so yield 1 executes the next method of knowing that the Walker is called before the function continues to execute. For this, resume execution after the Yeild declaration, in this case the yield2. The ability to stop execution inside a function is powerful, which leads to many interesting uses of generator functions. (discussed later)

yieldthe keyword can used with any value or expression, so can do interesting things as use inside of yield a Loop:

The yield keyword can be used with any value and expression, so you can use yield to do an interesting thing in a For loop:

function *createiterator (items) {for    (let i=0; i < items.length; i++) {        yield items[i];    }} Let iterator = Createiterator ([1, 2, 3]); Console.log (Iterator.next ());           "{value:1, Done:false}" Console.log (Iterator.next ());           "{value:2, Done:false}" Console.log (Iterator.next ());           "{Value:3, Done:false}" Console.log (Iterator.next ());           "{value:undefined, done:true}"//For all further Callsconsole.log (Iterator.next ());           "{value:undefined, done:true}"

In this example, an array are used in a for loops, yielding each item as the loop progresses. Each time yield was encountered, the loop stops, and each time are next() called on iterator , the loop picks back up where it Left off.

In this example, loop an array, and each loop outputs an entry for the array. Each time the yield is encountered, the loop stops, and each time the Walker's next method is called, the loop starts from where it was previously stopped.

Generator functions is an important part of ECMAScript 6, and since they is just functions, they can used in all the Same places.

Generators are an important part of ES6 because they are just functions, so they are the same as the use of functions.

Generator functions expressions-Generator function expressions

Not to be continued .... (translation is also a very tiring one)

Ecmascript6-iterators and generators

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.