为什么我的生成器经过迭代后变成空的? [英] Why does my generator become empty after being iterated through?

查看:60
本文介绍了为什么我的生成器经过迭代后变成空的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的库中的函数调用将生成器返回给我.然后,我将此生成器传递给一个函数,该函数对该函数进行迭代,并对每个项目进行一堆逻辑处理.然后,在该函数被调用之后,我想引用相同的生成器.但是,似乎生成器不再具有/生成任何项目.代码如下:

I have a generator being returned to me by a function call from a library I'm using. I then pass this generator to a function which iterates through it and does a bunch of logic on each of the items. I then want to refer to this same generator after that function has been called. However, it seems the generator no longer has/generates any items. The code is along these lines:

let myGenerator = this.generatorFunc();
console.log(Array.from(myGenerator).length); //prints N which is specified elsewhere
this.iterateThroughGenerator(myGenerator);
console.log(Array.from(myGenerator).length); //now prints 0 when I need it to be N still

iterateThroughGenerator(generator) {
    for(let element of generator) {
        // do a bunch of stuff with element
    }
}

推荐答案

其他人已经解释了为什么发生这种情况,但是我还是要回顾一下.

Others have already explained why this is happening, but I'll recap anyway.

生成器函数返回一个生成器对象,该对象同时实现了可迭代协议(迭代器协议(

Generator functions return a generator object, which implements both the iterable protocol (a Symbol.iterator property) using a simple circular reference to itself, and the iterator protocol (a next() method) in order to statefully iterate through the control flow of its generator function.

要解决您的问题,请通过返回生成器对象的单独实例,将生成器函数调用与一个实现可迭代协议的对象封装在一起,您可以使用相同的方式使用它:

To fix your problem, encapsulate the generator function call with an object that implements the iterable protocol by returning separate instances of your generator object, and you can use it the same way:

const iterable = { [Symbol.iterator]: () => this.generatorFunc() };

console.log(Array.from(iterable).length); //prints N which is specified elsewhere
this.iterateThroughGenerator(iterable);
console.log(Array.from(iterable).length); //still prints N

iterateThroughGenerator(iterable) {
    for(let element of iterable) {
        // do a bunch of stuff with element
    }
}

这篇关于为什么我的生成器经过迭代后变成空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆