javascript – for..of和迭代器状态

考虑一下这个 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,因为迭代器会记住它在循环中的状态.当我在JS中看似相同的事情时,我得到的只是1 2 3 —.

function* iter(a) {
    yield* a;
}

it = iter([1,5])

for (let x of it) {
    console.log(x)
    if (x === 3)
        break
}

console.log('---')

for (let x of it) {
    console.log(x)
}

我错过了什么?

解决方法

不幸的是,JS中的Generator对象不可重用.
MDN清楚地说明

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.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...