for...of 一个迭代器而不关闭它
for...of an iterator without closing it
是否可以在中断循环时使用 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;
}
是否可以在中断循环时使用 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;
}