Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 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 Answer

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); }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...