How can the current number of i be accessed in a for of loop?

前端 未结 6 1118
一个人的身影
一个人的身影 2020-12-03 20:54

Given a for of loop the value of the assigned the variable(i for this example) is equal to what array[i] would equal if it was a normal for loop. H

6条回答
  •  一个人的身影
    2020-12-03 21:36

    nothing simple ... if you want "simple access" to both the item and the index in a loop over an array, use forEach e.g.

    array.forEach(function(item, index) { 
    ... 
    });
    

    or as T.J. Crowder pointer out (and I missed the ES6 tag)

    array.forEach((item, index) => { 
        ... 
    });
    

    like many programming languages, javascript has multiple ways to do similar things, the skill is in choosing the right tool for the job

提交回复
热议问题