for..of和迭代器状态 [英] for..of and the iterator state
本文介绍了for..of和迭代器状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑此python代码
Consider this python code
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 ---
.
it prints 1 2 3 --- 4 5
, because the iterator it
remembers its state across the loops. When I do seemingly the same thing in JS, all I get is 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
Generator objects in JS are not reusable unfortunately. Clearly stated on MDN
即使for ... of循环是提前终止,例如通过break关键字终止.退出时循环,生成器关闭,并尝试再次对其进行迭代无法产生任何进一步的结果.
Generators should not be re-used, even if the for...of loop is terminated early, for example via the break keyword. Upon exiting a loop, the generator is closed and trying to iterate over it again does not yield any further results.
这篇关于for..of和迭代器状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文