16、forEach 如何终止循环

87 阅读1分钟

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

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 的实现原理如下:

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

try {
  arr.forEach((item, index) => {
    console.log("[ item ] >", item);
    if (item === 2) {
      throw new Error("error");
    }
  });
} catch (error) {}

2、数组长度置为 0

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

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