访问 for-of 循环中的 ES6 数组元素索引

2022-08-29 23:40:32

我们可以使用 for-of 循环访问数组元素:

for (const j of [1, 2, 3, 4, 5]) {
  console.log(j);
}

如何修改此代码以访问当前索引?我想使用for-of语法来实现这一点,既不是forEach也不是for-in。


答案 1

使用 Array.prototype.keys

for (const index of [1, 2, 3, 4, 5].keys()) {
  console.log(index);
}

如果要同时访问键和值,可以使用 Array.prototype.entries()析构

for (const [index, value] of [1, 2, 3, 4, 5].entries()) {
  console.log(index, value);
}

答案 2

Array#entries 返回索引和值,如果两者都需要:

for (let [index, value] of array.entries()) {

}