Home >Web Front-end >JS Tutorial >Detailed explanation of Generator generator in Javascript

Detailed explanation of Generator generator in Javascript

青灯夜游
青灯夜游forward
2021-01-02 09:25:562679browse

Detailed explanation of Generator generator in Javascript

What is a Generator?

A generator is some code that runs inside a function

  • After returning a value, it pauses itself, and -

  • The calling program can ask to unpause and return another value

This "return" is not a traditional slave functionreturn. So it was given a special name - yield.

Generator syntax varies from language to language. Javascript's generator syntax is similar to PHP's, but it's different enough that if you expect them to do the same thing, you'll end up getting very confused.

In javascript, if you want to use a generator, you need to:

  • Define a special generator function

  • Call this function to create a generator object

  • Use the generator object in a loop, or directly call its next method

We use the following simple program as a starting point and perform each of the following steps:

// File: sample-program.js
function *createGenerator() {
  for(let i=0;i<20;i++) {
    yield i
  }
}

const generator = createGenerator()

console.log(generator.next())
console.log(generator.next())

If you run this code, you will get the following output:

$ node sample-program.js

{ value: 0, done: false }
{ value: 1, done: false }

Here I go Explain how the program works.

Generator function

First, there is a definition of the generator function in the code:

function* createGenerator() {
  for(let i=0;i<20;i++) {
    yield i
  }
}

function followed by * Tells javascript that this is a generator function. The following writings are all valid definitions of generator functions.

function*createGenerator
function* createGenerator
function *createGenerator

* and are not part of the function name. Instead, the function* symbols define generators.

Call the generator function

After defining the generator function, we name it a function with another name.

// 注意:当调用时,没有 *。 * 不是函数名称的一部分
// `function *` 是用于定义生成器函数的符号
const generator = createGenerator()

But remember: createGenerator The function has no return value. This is because generator functions don't have traditional return values. In contrast, when you call a generator function directly, it always returns an instantiated Generator object.

This generator object has a next method. Calling next will run the code inside the generator function.

function* createGenerator() {
    for(let i=0;i<20;i++) {
        yield i
    }
}

This is important enough to call it again. Calling a generator function directly will not run any code within the generator function. Instead, create a generator object. It calls next on the generator object, thereby calling the code in the generator function.

The first time next is called on a generator object, the internal code will run until the yield statement occurs. Once execution reaches yield, javascript will pause the execution of that code, and next will return (i.e. to you, or yield) An object containing the values ​​in the yield rows.

When you call next a second time (or third, fourth or even more times), the code will unpause and continue running (as in the last call) where it was interrupted). The variable (such as i in this example) will retain its value. When the code reaches another yield statement, the function pauses again and returns an object containing the yield value.

This is why we have to call twice next

console.log(generator.next())
console.log(generator.next())

will get the following output:

{ value: 0, done: false }
{ value: 1, done: false }

After the code in the generator function is executed, Any future calls to next will return an object with the value undefined and done set to true.

{ value: undefined, done: true }

Generators and Loops

Although next can be called manually on the generator object, we mainly want to use it in a loop. Take a look at this slightly modified program.

// File: sample-program.js
@highlightsyntax@jscript
function *createGenerator() {
  for(let i=0;i<5;i++) {
    yield i
  }
}

const generator = createGenerator()
for(const value of generator) {
  console.log(value)
}

When using a generator object in a for...of loop, next is called on the generator object each time through the loop, with the resulting value Populate the variable (value above). Running this program will output the following:

$ node sample-program.js
0
1
2
3
4

In the next article, we will take a deeper look at for ... of loops and explore how to provide a built-in Method to loop through any object in javascript

English original address: https://alanstorm.com/javascript-generators/

Author: Alan Storm

Translation Address: https://segmentfault.com/a/1190000023924834

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Detailed explanation of Generator generator in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete
Previous article:How to uninstall Node.jsNext article:How to uninstall Node.js