In es6, the generator is a function that sets the iterator. Calling the generator function can return an iterable object; there is an "*" sign between the function and the function name in the generator, and the function The yield expression is used inside the body, and the syntax is "function*gen(){yield1;yield2;}".
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
The generator is a function used to set iterators in Es6. We can understand it this way: the generator ultimately generates an iterator.
Generator is a new data type introduced by the ES6 standard.
A generator looks like a function, but can return multiple times.
There are two differences between the generator function and the ordinary function,
1: There is an * between the function and the function name,
2: The yield expression is used inside the function body
Calling a generator function is different from calling a normal function. Calling a generator function returns a generator object (iterable Object)
Generator: There is an iterator interface in the generator, which means that the generator itself can be iterated, that is, creating a generator is equivalent to creating an iterator. Regarding the use of generators, for some data types that do not have an iterator interface, we can use a generator to customize an iterator for iteration.
The above is my understanding of the generator itself. The specific syntax is explained below.
Some properties of the generator
//生成器的声明 <script> function* generator(){ } let test = generator(); console.log(test); </script>
//生成器中的yield关键字 <script> function* Generator(){ yield 100; yield 200; yield 300; yield 400; } let test = Generator(); console.log(test.next()); console.log(test.next()); console.log(test.next()); console.log(test.next()); console.log(test.next()); console.log(test.next()); console.log(test.next()); </script>
Final result:
Parsing: Due to the generator instantiating the object There is next() in the prototype. When next() is executed, it will be iterated according to yield.
【Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of What does es6 generator mean?. For more information, please follow other related articles on the PHP Chinese website!