【发布时间】:2019-09-02 18:36:39
【问题描述】:
我很难调和这两者:
const gen = function *() {
yield 3;
yield 4;
return 5;
};
const rator = gen();
console.log(rator.next()); // { value: 3, done: false }
console.log(rator.next()); // { value: 4, done: false }
console.log(rator.next()); // { value: 5, done: true }
上面我们看到了所有 3 个值,如果我们第四次调用 next(),我们得到:
{ value: undefined, done: true }
这是有道理的。但是现在如果我们在循环中使用它:
for(let v of gen()){
console.log('next:', v); // next: 3, next: 4
}
我想我很困惑为什么使用 for 循环不打印 next: 5,但是手动调用迭代器上的 next() 可以获得 return 值。谁能解释这是为什么?
换句话说,我希望for loop 打印next: 5,但事实并非如此。
【问题讨论】:
-
一旦
done为真,for 循环就结束了。返回值不是迭代序列的一部分。它通常是未定义的。 -
正确,因此循环会丢弃第一个 done:true 对象附带的值。看起来很奇怪。
标签: javascript node.js generator coroutine