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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

If you are eager to find the top free AI animation art generator, you can end your search. The world of anime art has been captivating audiences for decades with its unique character designs, captivating colors and captivating plots. However, creating anime art requires talent, skill, and a lot of time. However, with the continuous development of artificial intelligence (AI), you can now explore the world of animation art without having to delve into complex technologies with the help of the best free AI animation art generator. This will open up new possibilities for you to unleash your creativity. What is an AI anime art generator? The AI Animation Art Generator utilizes sophisticated algorithms and machine learning techniques to analyze an extensive database of animation works. Through these algorithms, the system learns and identifies different animation styles
