遍历 ES6 中的生成器

Iterating through generator in ES6

本文关键字:ES6 遍历      更新时间:2023-09-26

this code

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);

返回

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);