本文最后更新于 2024-03-23T16:32:28+00:00
                  
                  
                
              
            
            
              
                
                结论:正常情况下是无法终止的
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;   } });
 
 
 
 
 
 
  | 
 
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 等提前结束