Нет встроенного способа сделать это - генератор должен будет дать что-то, что содержит индекс.Например:
function* myGen(){
let index = 0;
while(index < 10) {
const item = 'foo' + index;
yield { item, index };
index++;
}
}
for(const { item, index } of myGen()) {
console.log('item: ' + item);
console.log('index: ' + index);
}
Если вы не можете изменить генератор, для которого вы хотите получить индекс, вы можете поместить его в другой генератор, который отслеживает индекс (или вы можете просто увеличивать каждую внешнюю итерацию):
function* unmodifiableGen(){
// index is private, is not being yielded
let index = 0;
while(index < 10) {
yield Math.random();
index++;
}
}
function* generatorCounter(gen) {
// this index *will* be yielded:
let index = 0;
for (const item of gen()) {
yield { item, index };
index++;
}
}
for(const { item, index } of generatorCounter(unmodifiableGen)) {
console.log('item: ' + item);
console.log('index: ' + index);
}