这段代码
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);
关于javascript - 遍历 ES6 中的生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36895095/