Home > Web Front-end > JS Tutorial > body text

A brief discussion on the use of Generator and Iterator in JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 15:48:15
Original
1053 people have browsed it

When it comes to Generator, everyone will bring up topics such as asynchronous. This was obviously caused by something weird. Iterator should be closely related to Generator. Using Generator to handle asynchronous processing may be something only some C# programmers would think about. Of course, this usage does have a complete set of things, but I personally don't like it.
If you have to connect Generator with asynchronous, the only point is the timing of calling next. Because next can be called asynchronously, Generator can be abused asynchronously.
But I think that although the next method can be called asynchronously, the correct way to use it should be synchronously. At least when a Generator instance is used in a for-of loop or [...obj] destructuring, next is called continuously.
In addition to the synchronous and asynchronous issues of next, the parameters of next are also a problem. Since the parameters passed in when next is called will be used as the return value of the yield operator, generators have richer ways to use them. In early Python, yield was a statement rather than an operator, so there was no such usage. Later versions used yield as an operator, so various pitfalls appeared.
When using a Generator instance as an Iterator, next will not be called asynchronously, nor will next be passed in parameters. I think this is the correct usage of Generator. Or to put it bluntly, Generator is used to implement Iterator. At least the name Generator has no other meaning. Here is a usage example:
Run

<script>
var match = function * (pattern, string) {
 var regexp = new RegExp(pattern, 'g'); 
 for(let i; i = regexp.exec(string); yield i);
};

for(let i of match('a', 'abcabcabc')) {
 console.log(i);
}
</script>

Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template