给定提供的(非常简单)生成器,是否可以将生成器返回到其原始状态以再次使用?
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);
}
我希望能够将可迭代对象传递到其他范围,迭代它,做一些其他事情,然后能够稍后在同一范围内再次迭代它。
如果你的意图是
到其他范围,迭代它,做一些其他的事情,然后能够稍后在同一范围内再次迭代它。
那么你唯一不应该尝试做的就是传递迭代器,而不是传递生成器:
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)