Ответ 1
.forEach
уже обладает этой способностью:
var someArray = [9, 2, 5];
someArray.forEach((item, index) => {
console.log(item); // 9, 2, 5
console.log(index); // 0, 1, 2
});
Но если вы хотите возможности for...of
, вы можете map
массив к элементу и индексу:
for (const {item, index} of someArray.map((item, index) => ({ item, index }))) {
console.log(item); // 9, 2, 5
console.log(index); // 0, 1, 2
}
Это немного длиннее, поэтому он помогает бросить его в функцию многократного использования:
function toItemIndexes<T>(a: T[]) {
return a.map((item, index) => ({ item, index }));
}
for (const {item, index} of toItemIndexes(someArray)) {
// ..etc..
}
Итерируемая версия
Это будет работать при настройке ES3 или ES5, если вы компилируете с помощью параметра --downlevelIteration
компилятора.
function* toItemIndexes<T>(items: T[] | IterableIterator<T>) {
let index = 0;
for (const item of items) {
yield { item, index };
index++;
}
}