.forEach已经有这个能力了:
const someArray = [9, 2, 5];
someArray.forEach((value, index) => {
console.log(index); // 0, 1, 2
console.log(value); // 9, 2, 5
});
但是如果你想要for...of的能力,那么你可以map数组的索引和值:
for (const { index, value } of someArray.map((value, index) => ({ index, value }))) {
console.log(index); // 0, 1, 2
console.log(value); // 9, 2, 5
}
这有点长,所以把它放在一个可重用的函数中可能会有所帮助:
function toEntries<T>(a: T[]) {
return a.map((value, index) => [index, value] as const);
}
for (const [index, value] of toEntries(someArray)) {
// ..etc..
}
可迭代版本
如果您使用 --downlevelIteration 编译器选项进行编译,这将在针对 ES3 或 ES5 时起作用。
function* toEntries<T>(values: T[] | IterableIterator<T>) {
let index = 0;
for (const value of values) {
yield [index, value] as const;
index++;
}
}
Array.prototype.entries() - ES6+
如果您能够以 ES6+ 环境为目标,那么您可以使用Arnavion's answer 中所述的.entries() 方法。