ES6——Generator的next()方法

结论先行:

yield 句本身没有返回值,或者说总是返回 undefined 。 next 方法可以带一个参数,该参数就会被当作上一个 yield 语句的返回
值。

1. next()不带参数

function* gen(x) {
    for (var x of [1,2,3,4,5]){
        var y = yield (x + 2);
        return y;
    }
}
var g = gen(1);
console.log(g.next())  
console.log(g.next())  

2.next()带参数。

function* gen(x) {
    for (var x of [1,2,3,4,5]){
        var y = yield (x + 2);
        return y+20;
    }
}
var g = gen(1);
console.log(g.next())  
console.log(g.next(10))  

原文地址:https://www.cnblogs.com/sunupo/p/15483462.html