Iterators and generators in JavaScript _ javascript skills

Source: Internet
Author: User
This article mainly introduces the iterator and generator in JavaScript. This article describes the iterator, the Declaration custom iterator, And the generator: it is a better way to build the iterator, generator advanced features, and other content. If you need it, you can refer to it to process each item in the set as a very common operation, javaScript provides many methods to iterate a set, from a simple for and for each loop to map (), filter () and array comprehensions (array derivation ). In JavaScript 1.7, The iterator and generator bring new iteration mechanisms in the core JavaScript syntax, and also provide custom... In and for each.

Iterator

An iterator is an object that accesses an element in a set sequence and tracks the current position of iteration in the sequence. In JavaScript, The iterator is an object. This object provides a next () method, and the next () method returns the next element in the sequence. This method throws a StopIteration exception when all elements in the sequence are traversed.

Once an iterator object is created, you can call next () explicitly or use JavaScript... In and for each are implicitly called.

You can use Iterator () to create an Iterator that iterates on objects and arrays:

The Code is as follows:


Var lang = {name: 'javascript ', birthYear: 1995 };
Var it = Iterator (lang );

Once Initialization is complete, the next () method can be called to access the key-value pairs of objects in sequence:

The Code is as follows:


Var pair = it. next (); // the key-value pair is ["name", "JavaScript"]
Pair = it. next (); // the key-value pair is ["birthday", 1995]
Pair = it. next (); // A 'stopiteration' exception is thrown.

For... An in loop can be used to replace an explicit call to the next () method. When a StopIteration exception is thrown, the loop is automatically terminated.

The Code is as follows:


Var it = Iterator (lang );
For (var pair in it)
Print (pair); // each time a [key, value] key-value pair in it is output

If you only want to iterate the key value of an object, you can input the second parameter to the Iterator () function. The value is true:

The Code is as follows:


Var it = Iterator (lang, true );
For (var key in it)
Print (key); // output the key value each time.

One advantage of using Iterator () to access an Object is that the custom attributes added to Object. prototype are not included in the sequence Object.

Iterator () can also be used on Arrays:

The Code is as follows:


Var langs = ['javascript ', 'python', 'haskell'];
Var it = Iterator (langs );
For (var pair in it)
Print (pair); // output the [index, language] key-value pair for each iteration

Just like traversing an object, the result of passing true as the second parameter will be an array index:

The Code is as follows:


Var langs = ['javascript ', 'python', 'haskell'];
Var it = Iterator (langs, true );
For (var I in it)
Print (I); // output 0, followed by 1, followed by 2

You can use the let keyword to assign indexes and values to the block variables respectively within the loop, and Destructuring the values (Assignment ):

The Code is as follows:


Var langs = ['javascript ', 'python', 'haskell'];
Var it = Iterators (langs );
For (let [I, lang] in it)
Print (I + ':' + lang); // outputs "0: JavaScript", etc.

Declare a custom iterator

Some objects that represent the Element Set should be iterated in a specified way.

1. iteration of an object that represents a Range should return the numbers contained in this Range one by one.
2. The leaf nodes of a tree can be accessed with depth-first or breadth-first.
3. iterate an object that represents the database query results should be returned in one row, even if the entire result set is not fully loaded into a single array
4. The iterator acting on an infinite mathematical sequence (like the Fibonacci sequence) should return results one by one without creating an infinite-length data structure.

JavaScript allows you to write code for custom iteration logic and apply it to an object.

We create a simple Range object with two values: low and high:

The Code is as follows:


Function Range (low, high ){
This. low = low;
This. high = high;
}

Now we create a custom iterator that returns a sequence containing all integers in the range. The iterator interface requires us to provide a next () method to return the next element in the sequence or throw a StopIteration exception.

The Code is as follows:


Function RangeIterator (range ){
This. range = range;
This. current = this. range. low;
}
RangeIterator. prototype. next = function (){
If (this. current> this. range. high)
Throw StopIteration;
Else
Return this. current ++;
};

Our RangeIterator is instantiated through a range instance and maintains a current attribute to track the position of the current sequence.

Finally, to enable RangeIterator to combine with Range, we need to add a special _ iterator _ Method for Range. When we try to iterate a Range, it will be called and a RangeIterator instance that implements the iteration logic should be returned.

The Code is as follows:


Range. prototype. _ iterator _ = function (){
Return new RangeIterator (this );
};

After our custom iterator is complete, we can iterate a range instance:

The Code is as follows:


Var range = new Range (3, 5 );
For (var I in range)
Print (I); // output 3, then 4, then 5

Generator: a better way to build an iterator

Although custom iterators are useful tools, you need to carefully plan them when creating them because they need to be explicitly maintained.

The generator provides powerful functions: it allows you to define a function that contains your own iteration algorithm, and it can automatically maintain its own State.

A generator is a special function that can be used as an iterator factory. If a function contains one or more yield expressions, it is called a generator (Note: Node. js also needs to be represented by * Before the function name ).

Note: Only HTML is included in

Related Article

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.