在 js 做遍历数组的时候会用到很多数组的遍历方法,例如 for 循环、forEach 之类的方法,今天主要来说说 forEach 方法的一些坑。
来看一下这段代码:

1
2
3
4
5
6
7
let arr = [1, 2];
arr.forEach((item, indec) => {
arr.splice(index, 1);
console.log("执行"); // 输出了几次???
});

console.log(arr); // arr ????

上述代码中,循环体内“执行”打印了几次?arr 的输出是多少?

👌 好,我们带着这些疑问继续往下看。

forEach 参数

与 for 循环一样,forEach 也属于完整遍历数组的方法,并会对数组每项元素执行提供的回调函数,一个完整的 forEach 应该是这样,我们一一解释回调函数的参数,与后方的 this 有何作用。
arr.forEach(function(self,index,arr){},this)

  • **self**:数组当前遍历的元素,默认从左往右依次获取数组元素
  • **index**:数组当前元素的索引
  • **arr**:当前遍历的数组
  • **this**:回调函数中的 this 指向
1
2
3
4
5
6
7
8
9
let arr = [1, 2, 3, 4];
let obj = {
a: 1,
};
arr.forEach(function (self, index, arr) {
console.log(`当前元素为${self}索引为${index},属于数组${arr}`);
//做个简单计算
console.log(self + this.a);
}, obj);

可以看到,arr 参数其实就是我们正在遍历的数组,而回调函数中的 this 指向我们提供的 obj。

至于第三个参数 arr,遍历自己还提供自己作为参数,其实这个参数还挺好用,比如我们可以利用它做数组去重,像这样:

1
2
3
4
5
6
let arr1 = [1, 2, 3, 2, 1, 4];
let arr2 = [];
arr1.forEach((self, index, arr) => {
arr.indexOf(self) === index ? arr2.push(self) : null;
});
console.log(arr2); // [1,2,3,4]

坑点

1、不支持 break

大家都知道,在使用 for 循环时可以使用 break 跳出循环,比如我希望找到数组中符合条件的第一个元素就跳出循环,这对于优化数组遍历是非常棒的。很遗憾,forEach 并不支持 break 操作,使用 break 会导致报错。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let arr = [1, 2, 3, 4], i = 0, length = arr.length;
for (; i < length; i++) {
console.log(arr[i]); //1,2
if (arr[i] === 2) {
break;
};
};

arr.forEach((self,index) => {
console.log(self);
if (self === 2) {
break; //报错
};
});

要想跳过循环,需要通过 try catch 来操作;具体可以查看文章js forEach 跳出循环

2、使用 return 无效

forEach 中使用 return 不会报错,但 rerutn 并不会生效,我们来看个例子:

1
2
3
4
5
6
7
8
9
let arr = [1, 2, 3, 4];
function find(arr, num) {
arr.forEach((self, index) => {
if (self === num) {
return index;
}
});
}
let index = find(arr, 2); // undefined

上述代码想要找到数字 2 在数组中的索引,但 return 并不会起到终止代码运行并返回值的作用。
如果我们真的要用 return 返回某个值,那就只能将 return 操作放在函数中,而不是 forEach 循环中,像这样:

1
2
3
4
5
6
7
8
9
function find(arr, num) {
let _index;
arr.forEach((self, index) => {
if (self === num) {
_index = index;
}
});
return _index;
}

3、删除自身元素 index 不会被重置

让我们回头看看文章开头的那段代码,那段代码其实只会执行一次,数组也不会被删除干净,这是因为 forEach 在遍历跑完回调函数后,会隐性让 index 自增,像这样:

1
2
3
4
5
6
arr.forEach((item, index) => {
arr.splice(index, 1);
console.log("执行");
//这里隐性让index自增加1
index++;
});

当第一次遍历结束,此时数组为[2]而 index 变成了 1,此时数组最大索引只是 0,不满足条件,所以跳出了循环。
那有没有什么办法让此时的 forEach 不跳出循环呢,当然有,使用 ES6 的拓展运算符。

1
2
3
4
[...arr].forEach((item, index) => {
arr.splice(index, 1);
console.log("执行");
});

通过拓展运算符重置数组 arr,达到不跳出循环的目的,会发现内部确实执行了两次,很遗憾的是 index 依旧没被重置,所以数组 arr 还是无法在遍历的同时删空自己。


for、forEach 比较

  1. for 循环可以使用 break 跳出循环,但 forEach 不能。
  2. for 循环可以控制循环起点(i 初始化的数字决定循环的起点),forEach 只能默认从索引 0 开始。
  3. for 循环过程中支持修改索引(修改 i),但 forEach 做不到(底层控制 index 自增,我们无法左右它)。

数组遍历并删除自身

怎么在遍历一个数组的同时,并删除符合条件的所有项呢?

for 循环实现

1
2
3
4
5
6
7
8
9
10
11
12
13
let arr = [1, 2, 1],
i = 0,
length = arr.length;

for (; i < length; i++) {
// 删除数组中所有的1
if (arr[i] === 1) {
arr.splice(i, 1);
//重置i,否则i会跳一位
i--;
}
}
console.log(arr); // [2]

filter 实现

1
2
3
4
var arr1 = arr.filter((index) => {
return index !== 1;
});
console.log(arr1); //[2]

forEach 实现(不建议)

forEach 因为 index 索引无法重置,对于删除数组项真的很困难,我们得让数组反过来遍历:

1
2
3
4
5
6
7
8
9
arr
.slice()
.reverse()
.forEach(function (item, index, arr1) {
if (item === 1) {
arr.splice(arr1.length - 1 - index, 1);
}
});
console.log(arr); //[2]