js中数组遍历的几种方式

前言

最近学习前端项目时学到了数组这块,遍历数组有好多种方式,下面详细记录下,方便后面项目中使用

for 循环
1
2
3
4
for (let index=0; index < someArray.length; index++) {
const elem = someArray[index];
// ···
}

该方式是最基础的方式,如果我们遍历时不想从第一个元素开始,这种方式会很好用,其他方式要做到会很复杂

for-in 循环
1
2
3
for (const key in someArray) {
console.log(key);
}

该循环遍历的是key,不是值,我们一般都是遍历其中的值,所以大部分情况下不太符合我们的要求

数组方法 .forEach()
1
2
3
someArray.forEach((elem, index) => {
console.log(elem, index);
});

该方式是数组的方法,是es6中推出的,大部分情况我用的都是forEach,如果需要index索引,用第二种方式,否则直接用第一种,非常简洁,推荐使用

缺点是这种方式不能提前退出循环,for中可以使用break退出,循环体中不能使用await关键字

for-of 循环:
1
2
3
for (const elem of someArray) {
console.log(elem);
}

for-of 在循环遍历数组时非常有效:

  • 用来遍历数组元素。
  • 可以使用 await
    • 如果有需要,可以轻松地迁移到 for-await-of
  • 甚至可以将 breakcontinue 用于外部作用域。
for-of 和可迭代对象

for-of 不仅可以遍历数组,还可以遍历可迭代对象,例如遍历 Map:

1
2
3
4
5
6
7
8
9
10
11
const myMap = new Map()
.set(false, 'no')
.set(true, 'yes')
;
for (const [key, value] of myMap) {
console.log(key, value);
}

// Output:
// false, 'no'
// true, 'yes'

遍历 myMap 会生成 [键,值] 对,可以通过对其进行解构来直接访问每一对数据。

for-of 和数组索引

数组方法 .entries() 返回一个可迭代的 [index,value] 对。如果使用 for-of 并使用此方法进行解构,可以很方便地访问数组索引:

1
2
3
4
5
6
7
8
9
const arr = ['chocolate', 'vanilla', 'strawberry'];

for (const [index, elem] of arr.entries()) {
console.log(index, elem);
}
// Output:
// 0, 'chocolate'
// 1, 'vanilla'
// 2, 'strawberry'