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
491 views
in Technique[技术] by (71.8m points)

javascript - 在for-of循环中访问ES6数组元素索引(Access to ES6 array element index inside for-of loop)

We can access array elements using a for-of loop:(我们可以使用for-of循环访问数组元素:)

for (const j of [1, 2, 3, 4, 5]) { console.log(j); } How can I modify this code to access the current index too?(如何修改此代码也可以访问当前索引?) I want to achieve this using for-of syntax, neither forEach nor for-in.(我想使用for-of语法来实现此目的,无论是forEach还是for-in。)   ask by Abdennour TOUMI translate from so

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

1 Reply

0 votes
by (71.8m points)

Use Array.prototype.keys :(使用Array.prototype.keys :)

for (const index of [1, 2, 3, 4, 5].keys()) { console.log(index); } If you want to access both the key and the value, you can use Array.prototype.entries() with destructuring :(如果要访问键和值,则可以将Array.prototype.entries()destructuring一起使用 :) for (const [index, value] of [1, 2, 3, 4, 5].entries()) { console.log(index, value); }

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

...