考虑这个Python代码
it = iter([1, 2, 3, 4, 5])
for x in it:
print x
if x == 3:
break
print '---'
for x in it:
print x
它打印1 2 3 --- 4 5
,因为迭代器it
记住它在循环中的状态。当我在 JS 中做看似相同的事情时,我得到的只是1 2 3 ---
.
function* iter(a) {
yield* a;
}
it = iter([1, 2, 3, 4, 5])
for (let x of it) {
console.log(x)
if (x === 3)
break
}
console.log('---')
for (let x of it) {
console.log(x)
}
我缺少什么?
不幸的是,JS 中的生成器对象不可重用。
明确指出MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of#Do_not_reuse_generators
生成器不应重复使用,即使 for...of 循环是
提前终止,例如通过break关键字。退出时
循环,生成器关闭并尝试再次迭代它
不会产生任何进一步的结果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)