写for写习惯了,都忘了foreach里面没有break continue关键字了,也不能用return跳出循环,但是可以用return实现continue功能,结束单次遍历

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.forEach((a) => {
  if (a % 2 == 0) {
    return;
  }
  console.log("a:", a);
});

在这里插入图片描述
用try catch可以跳出foreach遍历

try {
  let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  arr.forEach((a) => {
    if (a % 2 == 0) {
      throw "跳出foreach";
      return;
    }
    console.log("a:", a);
  });
} catch (error) {
  console.log("error:", error);
}

在这里插入图片描述

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐