在 for-of 循环中访问 ES6 数组元素索引 [英] Access to ES6 array element index inside for-of loop
本文介绍了在 for-of 循环中访问 ES6 数组元素索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们可以使用 for-of 循环访问数组元素:
We can access array elements using a for-of loop:
for (const j of [1, 2, 3, 4, 5]) {
console.log(j);
}
如何修改此代码以访问当前索引?我想使用 for-of 语法来实现这一点,既不是 forEach 也不是 for-in.
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 (const index of [1, 2, 3, 4, 5].keys()) {
console.log(index);
}
如果你想同时访问key和value,你可以使用Array.prototype.entries()
和 解构:
If you want to access both the key and the value, you can use Array.prototype.entries()
with destructuring:
for (const [index, value] of [1, 2, 3, 4, 5].entries()) {
console.log(index, value);
}
这篇关于在 for-of 循环中访问 ES6 数组元素索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文