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

前端 未结 6 1108
一个人的身影
一个人的身影 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:32

    You can use the entries function. It will return a index/value pair for each entry in the array like:

    [0, "one"]
    [1, "two"]
    [2, "three"]
    

    Use this in tandem with array destructuring to resolve each entry to the appropriate variable name:

    const arr = ["one", "two", "three"]
    for(const [index, value] of arr.entries()) {
      console.log(index, value);
    }
    

    Babel REPL Example

提交回复
热议问题