es6怎么遍历数组对象

es6
262
2024/1/5 17:07:55
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在ES6中,我们可以使用for...of循环来遍历数组对象。

例如,下面是一个数组对象的示例:

const arr = [1, 2, 3, 4, 5];

for (let item of arr) {
  console.log(item);
}

输出结果:

1
2
3
4
5

注意,for...of循环遍历的是数组对象的值,而不是下标。如果需要遍历下标,可以使用Array.prototype.entries()方法来获取下标和值的迭代器。

const arr = [1, 2, 3, 4, 5];

for (let [index, value] of arr.entries()) {
  console.log(index, value);
}

输出结果:

0 1
1 2
2 3
3 4
4 5

除了for...of循环,还可以使用Array.prototype.forEach()方法来遍历数组对象。

const arr = [1, 2, 3, 4, 5];

arr.forEach((item, index) => {
  console.log(index, item);
});

输出结果:

0 1
1 2
2 3
3 4
4 5

这些是在ES6中遍历数组对象的几种常用方法,根据具体需求选择适合的方法即可。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: es6对象扩展运算符怎么应用