javascript - 如何使用索引迭代生成器?

标签 javascript ecmascript-6 generator

使用 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/

相关文章:

javascript - ES6解构对象赋值函数参数默认值

javascript - 我的函数声明中哪一个更好?生成器还是异步/等待?

python - 从文本 block 动态生成生成器函数

javascript - 在 Vue.js v2.x 中使用 v-for 指令时如何指定范围的起始值?

javascript - 为什么我用于更改 (onclick) div 不透明度的 javascript 代码失败?

javascript - Angular 2 : execute a function when the element appears on the screen

javascript - 如何正确地将自定义数据属性 Prop 传递给子组件?

javascript - 获取可拖动标记的位置

javascript - 将对象添加到深层嵌套对象

python - 如何调整for循环的重复次数?