16、forEach 如何终止循环

结论:正常情况下是无法终止的

1
2
3
4
5
6
7
8
9
10
11
12
const arr = [1, 2, 3, 4];
arr.forEach((item, index) => {
console.log("[ item ] >", item);
if (item === 2) {
return;
}
});

// [ item ] > 1
// [ item ] > 2
// [ item ] > 3
// [ item ] > 4

forEach 的实现原理如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Array.prototype.forEach2 = function (callback) {
if (typeof callback !== "function") {
throw new Error(callback + " is not a function");
}

const len = this.length;
let i = 0;

while (i < len) {
if (this.hasOwnProperty(i)) {
callback(this[i], i, this);
}
i++;
}
};

所以正常情况下是无法终止 forEach 的

特殊处理可实现终止
1、抛出错误:try…catch + throw

1
2
3
4
5
6
7
8
try {
arr.forEach((item, index) => {
console.log("[ item ] >", item);
if (item === 2) {
throw new Error("error");
}
});
} catch (error) {}

2、数组长度置为 0

1
2
3
4
5
6
arr.forEach((item, index) => {
console.log("[ item ] >", item);
if (item === 2) {
arr.length = 0;
}
});

结论:当需要终止循环时,不建议使用 forEach 了,可以使用 for、for…of 等处理终止,也可使用 find、some 等提前结束


16、forEach 如何终止循环
https://mrhzq.github.io/职业上一二事/前端面试/每日一题/16、forEach 如何终止循环/
作者
黄智强
发布于
2024年1月23日
许可协议