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

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

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


当前回答

另一种方法是使用Array.prototype.forEach() as

Array.from ({ 长度:5 }, () => Math.floor(Math.random() * 5))。forEach((val, index) => { console.log (val,索引) })

其他回答

在这个花哨的新本地函数的世界里,我们有时会忘记基本的东西。

for (let i = 0; i < arr.length; i++) {
    console.log('index:', i, 'element:', arr[i]);
}

干净,高效,你仍然可以打破循环。奖金!你也可以从结尾开始,用i——!

额外注意:如果你在循环中经常使用这个值,你可能希望执行const value = arr[i];在循环的顶部为一个简单的,可读的参考。

另一种方法是使用Array.prototype.forEach() as

Array.from ({ 长度:5 }, () => Math.floor(Math.random() * 5))。forEach((val, index) => { console.log (val,索引) })

使用Array.prototype.keys:

对于[1,2,3,4,5].keys()的const索引{ console.log(指数); }

如果你想同时访问键和值,你可以使用Array.prototype.entries()进行解构:

For (const [index, value] of [1,2,3,4,5].entries()) { console.log(指数、价值); }

数组#entries返回索引和值,如果你需要两者:

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

}

如果你需要索引,你也可以自己处理索引,如果你需要键,它将不起作用。

let i = 0;
for (const item of iterableItems) {
  // do something with index
  console.log(i);

  i++;
}