鉴于提供的(非常简单的)生成器,是否可以将生成器返回到其原始状态以再次使用?
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/