gpt4 book ai didi

javascript - for...的迭代器而不关闭它

转载 作者:行者123 更新时间:2023-12-05 00:31:04 29 4
gpt4 key购买 nike

是否可以使用 for...of 循环遍历迭代器的一部分?中断循环时不关闭迭代器?
例子:

function* numbers(i=0){
while(true) yield i++;
}

let nums=numbers();

// this loop prints numbers from 0 to 3
for(const n of nums){
if(n>3) break;
console.log(n);
}

// this loop doesn't print anything because `nums` has already been closed
for(const n of nums){
if(n>10) break;
console.log(n);
}

我知道我可以通过自己调用 iterator.next() 来遍历迭代器.但我想知道是否可以使用 for...of句法。

最佳答案

不可以。但是您可以提供不转发 return() 的包装器。到发电机:

function unclosed(iterable) {
return {
[Symbol.iterator]() {
const iterator = iterable[Symbol.iterator]();
return {
next: iterator.next.bind(iterator),
return: null,
throw: null,
};
},
};
}

function* numbers(i=0) {
try {
while (true) yield i++;
} finally {
console.log('done');
}
}

const nums = numbers();

// this loop prints numbers from 0 to 3
for (const n of unclosed(nums)) {
console.log(n);
if (n == 3) break;
}
// and this one the numbers from 4 to 10, as well as 'done'
for (const n of nums) {
console.log(n);
if (n == 10) break;
}

关于javascript - for...的迭代器而不关闭它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71555057/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com