javascript - 是否可以将 ECMAScript 6 生成器重置为初始状态?

标签 javascript generator ecmascript-harmony ecmascript-6

鉴于提供的(非常简单的)生成器,是否可以将生成器返回到其原始状态以再次使用?

var generator = function*() {
    yield 1;
    yield 2;
    yield 3;
};

var iterable = generator();

for (let x of iterable) {
    console.log(x);
}

// At this point, iterable is consumed.
// Is there a method for moving iterable back
// to the start point by only without re-calling generator(),
// (or possibly by re-calling generator(), only by using prototype 
//  or constructor methods available within the iterable object)
// so the following code would work again?

for (let x of iterable) {
    console.log(x);
}

我希望能够将 iterable 传递给其他范围,对其进行迭代,做一些其他事情,然后能够稍后在同一范围内再次对其进行迭代。

最佳答案

如果你的意图是

to some other scope, iterate over it, do some other stuff, then be able to iterate over it again later on in that same scope.

那么你唯一不应该尝试做的就是传递迭代器,而是传递生成器:

var generator = function*() {
    yield 1;
    yield 2;
    yield 3;
};

var user = function(generator){

    for (let x of generator()) {
        console.log(x);
    }

    for (let x of generator()) {
        console.log(x);
    }
}

或者只是制作一个“循环”迭代器并在迭代时检查

var generator = function*() {
    while(true){
        yield 1;
        yield 2;
        yield 3;
    }
};

for( x in i ){
    console.log(x);
    if(x === 3){
        break;
    }
}

关于javascript - 是否可以将 ECMAScript 6 生成器重置为初始状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23848113/

相关文章:

javascript - 如何删除对象的键和值之间的空格

javascript - 光泽热图 Highcharts

JSON 和 ES6 映射和集合?

javascript - 使用 JS/jQuery 删除 WordPress 页面中 div 内的最后一个逗号

javascript - 围绕不断变化的原点旋转 - Javascript

javascript - 在 JS 中的生成器上调用 join()

Python的itertools乘积内存消耗

Python - 此代码是否缺少列表推导和生成器

javascript - 如何在 ES.Next 中编写库

javascript - Koa框架中JavaScript函数定义中的星号(*)是什么意思?