使用 javascript 中的数组,获取迭代的当前索引很容易。您可以使用 forEach
并且索引是第二个条目,或者使用 for...of
和 .entries()
以及数组解包。
但是生成器没有 .entries()
方法。如何获取 for...of
循环中生成器的当前索引?
我基本上想要:
function* myGen(){
let i = 0;
while(true) {
i+=1;
yield i;
}
}
for(let [j, index] of myGen().entries()) { //<-- I want .entries() but for a Generator
//...
}
//Running the above produces TypeError: myGen(...).entries(...) is not a function or its return value is not iterable
最佳答案
不建议向内置原型(prototype)添加内容,但如果您确实希望代码像那样工作(在任何生成器上调用 .entries()
),那么您可以继续如下:
const Generator = Object.getPrototypeOf(function* () {});
Generator.prototype.entries = function * () {
let i = 0;
for (let value of this) {
yield [i++, value];
}
}
// Demo
function* myGen(){
let i = 64;
while(i < 70) {
i+=1;
yield String.fromCharCode(i);
}
}
for(let [j, index] of myGen().entries()) { //<-- Now you have .entries() on a Generator
console.log(j, index);
}
然而,定义一个效用函数更为谨慎。
const GeneratorUtils = {
* entriesOf(iter) {
let i = 0;
for (let value of iter) {
yield [i++, value];
}
}
};
// Demo
function* myGen(){
let i = 64;
while(i < 70) {
i+=1;
yield String.fromCharCode(i);
}
}
for(let [j, index] of GeneratorUtils.entriesOf(myGen())) {
console.log(j, index);
}
关于javascript - 如何使用索引迭代生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53687210/