遍历 ES6 中的生成器

Iterating through generator in ES6

此代码

let func = function *(){
    for (let i = 1; i < 5; i++) {
        yield i;
    }
}
let s = func().next();
console.log(s);
let s2 = func().next();
console.log(s2);

returns

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

所以基本上 func 总是产生第一个值。

但是当我换成

let f = func();
let s = f.next();
console.log(s);
let s2 = f.next();
console.log(s2);

它按预期工作。 为什么将 func 分配给变量会产生如此大的差异?

在您的第一段代码中,您总是在创建一个新的生成器实例。我已将这些实例分配给单独的变量以更清楚地说明这一点:

// first generator instance
let g = func();
// first call to next on the first instance
let s = g.next();
console.log(s);
// second generator instance
let g2 = func();
// first call to next on the second instance
let s2 = g2.next();
console.log(s2);

而在您的第二个代码段中,您不断迭代相同的生成器(分配给变量 f):

let f = func();
// first call to next
let s = f.next();
console.log(s);
// second call to next
let s2 = f.next();
console.log(s2);