迭代 javascript

A for-of loop, introduced in ES6, is a great way to iterate over an array:

ES6中引入的for-of循环是一种遍历数组的好方法:

for (const v of ['a', 'b', 'c']) {
  console.log(v)
}

How can you get the index of an iteration?

如何获得迭代索引?

The loop does not offer any syntax to do this, but you can combine the destructuring syntax introduced in ES6 with calling the entries() method on the array:

循环不提供任何语法来执行此操作,但是您可以将ES6中引入的解构语法与调用数组上的entrys entries()方法结合使用:

for (const [i, v] of ['a', 'b', 'c'].entries()) {
  console.log(i, v)
}

翻译自: https://flaviocopes.com/how-to-get-index-in-for-of-loop/

迭代 javascript

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐