Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

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

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. How can the index of the array the that i is currently on be accessed.

What I want

let array = ["one", "two", "three"];

for (let i of array) {
  console.log(i);// normally logs cycle one : "one", cycle two : "two", cycle three : "three".
  console.log(/*what equals the current index*/);// what I want to log cycle one : 1, cycle two : 2, cycle three : 3. 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...