访问内部的ES6数组元素索引for-of循环 [英] Access to ES6 array element index inside for-of loop

查看:185
本文介绍了访问内部的ES6数组元素索引for-of循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用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, not forEach or for-in.

推荐答案

使用 Array.prototype.keys

for (const index of [1, 2, 3, 4, 5].keys()) {
  console.log(index);
}

如果要访问密钥和值,可以使用 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);
}

这篇关于访问内部的ES6数组元素索引for-of循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆