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

后端 未结 11 1973
走了就别回头了
走了就别回头了 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:27

    To use for..of loop on array and retrieve index you can you use array1.indexOf(element) which will return the index value of an element in the loop. You can return both the index and the value using this method.

    array1 = ['a', 'b', 'c']
    for (element of array1) {
        console.log(array1.indexOf(element), element) // 0 a 1 b 2 c
    }

提交回复
热议问题