溫馨提示×

es6怎么遍歷數組對象

es6
小億
148
2023-12-21 17:07:55
欄目: 編程語言

在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中遍歷數組對象的幾種常用方法,根據具體需求選擇適合的方法即可。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女