Understand what a JavaScript generator is in ten minutes (organized and shared)

WBOY
Release: 2021-12-21 18:40:11
forward
2918 people have browsed it

This article brings you knowledge about JavaScript generators, how generators are implemented, and the use of generator functions to customize iterators. I hope it will be helpful to you.

Understand what a JavaScript generator is in ten minutes (organized and shared)

1. What is a generator?

can be understood as a traverser of the internal state of a function. Every time the generator is called, the internal state of the function changes.


2. There is an asterisk between

  • #functionand the function name*
  • yieldexpressions can be used inside the function body to define different states

3. How is the generator implemented?

  • There is anextmethod in the generator, which traverses the next state
  • yieldExpression: equivalent to the pause flag, only callingnextmethod will traverse the next internal state
  • When using thenextmethod, execution starts from the beginning of the function or where it last stopped until it encounters Until the nextyieldexpression (orreturnstatement)
    (that is, the generator function is equivalent to a function that can suspend execution,yieldexpression The formula is the pause sign)

Let us understand it through an example:
(Take the familiar Hello World!!!)

function* sayHW(){ yield "Hello"; yield "World"; return "!!!";}let say = sayHW();console.log(say.next());console.log(say.next());console.log(say.next());
Copy after login

Understand what a JavaScript generator is in ten minutes (organized and shared)

Thenextmethod is called three times in total:

When called for the first time, it encountersyieldand stops,nextmethod Returns an object whosevalueattribute is the value of the currentyieldexpressionHello, and the value of thedoneattribute isfalse, indicating that the traversal has not ended

When calling for the second time, it stops when encounteringyield, and thenextmethod returns an object with itsvalueThe attribute is the value of the currentyieldexpressionWorld, and the value of thedoneattribute isfalse, indicating that the traversal has not ended

Then until the third call, execution reaches thereturnstatement (if not, execution continues until the end of the function). At this time, the value of thevalueattribute returned bynextis the value after thereturnstatement, and the attribute ofdoneistrue(If there is noreturn,doneis stillfalseat this time), indicating the end of the loop.

Next, we output againnext:

console.log(say.next());
Copy after login

Understand what a JavaScript generator is in ten minutes (organized and shared)
At this timenextwill return this object,valueisundefined,doneis ·true(regardless of whether there is areturnstatement before, the function has already been run at this time It’s done, sodoneare alltrue)


4. Use the generator function to customize the iterator

As explained above , we can know that the generator function allows us to define afunctionthat contains its own iteration algorithm, and at the same time it can automatically maintain its own state.

Since custom iterators need to maintain their internal state explicitly, we can use it to customize iterators.
(If you don’t know about iterators, you can read this article first: JavaScript iterators)

Next, let us understand it through an example:

Now there is acolorsobject, we want to usefor...ofto traverse it, then we can customize the iterator.

let colors = { blue : "蓝色", green : "绿色", yellow : "黄色"}
Copy after login

Normal writing:

colors[Symbol.iterator] = function() { let keys = Object.keys(colors); // 如果用 let keys = Reflect.ownKeys(colors),keys 就会包括一些不可枚举的属性 // 那么后面的 len 要减一,减去Symbol.iterator这个属性 // 根据实际情况选择使用 let len = keys.length; let index = 0; return { next : function() { if (index 

Writing using generator function:

colors[Symbol.iterator] = function* () { let keys = Object.keys(colors); // 如果用 let keys = Reflect.ownKeys(colors),包括了一些不可枚举的属性 // 那么后面的 len 要减一,减去Symbol.iterator这个属性 // 根据实际情况选择使用 let len = keys.length; let index = 0; while(index 

Understand what a JavaScript generator is in ten minutes (organized and shared)

That's it. After using the generator function to customize the iterator, it is much simpler.

[Related recommendations: javascript learning tutorial]

Copy after login

The above is the detailed content of Understand what a JavaScript generator is in ten minutes (organized and shared). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!