【问题标题】:Iterating through generator in ES6在 ES6 中遍历生成器
【发布时间】:2016-08-22 01:29:52
【问题描述】:

这段代码

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 分配给变量会产生如此大的差异?

【问题讨论】:

  • 因为func() !== func()?
  • 如果它的行为不同,那么每个生成器函数只能使用一次...

标签: javascript ecmascript-6 generator yield


【解决方案1】:

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

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

而在您的第二个 sn-p 中,您继续迭代同一个生成器(分配给变量 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);

【讨论】:

    猜你喜欢
    • 2016-11-05
    • 2021-12-28
    • 2014-07-20
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    相关资源
    最近更新 更多