Get loop counter/index using for…of syntax in JavaScript

后端 未结 11 1975
走了就别回头了
走了就别回头了 2020-11-28 00:55

Caution:

question still applies to for…of loops.> Don\'t use for…in to iterate over an Array, use it

11条回答
  •  被撕碎了的回忆
    2020-11-28 01:15

    In ES6, it is good to use for - of loop. You can get index in for of like this

    for (let [index, val] of array.entries()) {
            // your code goes here    
    }
    

    Note that Array.entries() returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.

提交回复
热议问题