New feature 3 of ES6: Generator (Generator) function details, es6 function details

Source: Internet
Author: User

New feature 3 of ES6: Generator (Generator) function details, es6 function details

This example describes the new feature 3 of ES6: Generator (Generator) function. We will share this with you for your reference. The details are as follows:

1. Introduction

① Understanding: it can be understood as a function's internal state traversal device. Each call changes the internal state of the function once.

② Writing:

function* f() {}

③ Function: it can completely control the changes in the internal state of the function and traverse these states in sequence.

④ Running process: When the Generator function is called, the function does not execute, but returns a traversal (which can be understood as pausing execution ). Start execution by calling next (). When yield stops execution, an object whose value attribute value is the value of the current yield statement, and whose done attribute is false is returned, which calls next () cyclically (), continue to the return Statement (if there is no return statement, it will be executed until the end of the function ). The value Attribute of the object returned by the next method is the value of the expression following the return statement (if there is no return statement, the value of the value attribute is undefined). The value of the done attribute is true, indicates that the traversal has ended.

Example:

Function * helloWorldGenerator () {yield 'hel'; yield 'World'; return 'ending';} var hw = helloWorldGenerator (); // This method is not executed when it is called for the first time, returns only one iterator. Var a = hw. next (); while (! A. done) {// when return is executed,. done = true, terminate the cyclic console. log (. value + ',' +. done); a = hw. next ();} console. log (. value + ',' +. done );

Result:

hello,falseworld,falseending,true

2. Parameters of next ()

① We Need To Know That next () returns an object,The yield statement itself does not return a value., Or always returns undefined. The next method can contain a parameter, which is treated as the return value of the previous yield statement.

Function * f () {for (var I = 0; true; I ++) {var reset = yield I; console. log (reset); // print the reset and verify that the yield statement has no returned value. if (reset) {I =-1 ;}} var g = f (); console. log (g. next () // {value: 0, done: false} console. log (g. next () // {value: 1, done: false} console. log (g. next (true) // {value: 0, done: false}

Result:

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

Through the parameters of the next method, you can continue injecting values into the function body after the Generator function starts to run. In other words, different values can be injected from the external to the internal in different stages of the Generator function operation to adjust the function behavior.

② Because the parameters of the next method represent the return values of the previous yield statement, parameters cannot be included when you use the next method for the first time. The V8 engine directly ignores the parameters when the next method is used for the first time. The parameters are valid only when the next method is used for the second time.

function* foo(x) { var y = 2 * (yield (x + 1)); var z = yield (y / 3); return (x + y + z);}var it = foo(5);console.log(it.next(3))// { value:6, done:false }console.log(it.next(12))// { value:8, done:false }console.log(it.next(13))// { value:42, done:true }

3. for-of traversal of generator

For... of loop can automatically traverse the Generator function, and you do not need to call the next method at this time,

Once the done attribute of the returned object of the next method is true, the for... of loop is aborted and does not contain the returned object.

function *foo() { yield 1; yield 2; yield 3; yield 4; yield 5; return 6;}for (let v of foo()) { console.log(v);}// 1 2 3 4 5

4. yield * Statement

① If the yield command is followed by a traversal tool, you need to add an asterisk after the yield command,Indicates that it returns a traversal.. This is called the yield * Statement.

let a = (function* () { yield 'Hello!'; yield 'Bye!';}());let b = (function* () { yield 'Greetings!'; yield* a; yield 'Ok, bye.';}());for(let value of b) { console.log(value);}

Result:

Greetings!Hello!Bye!Ok, bye.

② If no star number is added after the yield command, the entire array is returned. If an asterisk is added, the returned array is the traversal tool.

function* gen(){ yield* ["a", "b", "c"];}gen().next() // { value:"a", done:false }

Traverse nested Arrays:

function* iterTree(tree) { if (Array.isArray(tree)) { for(let i=0; i < tree.length; i++) {  yield* iterTree(tree[i]); } } else { yield tree; }}const tree = [ 'a', ['b', 'c'], ['d', 'e'] ];for(let x of iterTree(tree)) { console.log(x);}// a b c d e

I hope this article will help you design the ECMAScript program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.