JavaScript中如何终止forEach循环,跳出双层For循环?

在JavaScript中,forEach方法是用于遍历数组的,通常没有直接终止循环的机制。然而,我们可以使用一些技巧来模拟终止forEach循环。以下是几种常见的方法

1.使用return语句

forEach回调函数内部使用return语句可以实现类似终止循环的效果。当需要终止循环时,可以在回调函数中返回false或者任意其他特定值。

const arr = [1, 2, 3, 4, 5, 6, 7];
let terminate = false;

arr.forEach((element) => {
  if (terminate) {
    return;
  }

  console.log(element);

  if (element === 3) {
    terminate = true; // 终止循环
  }
});

2.使用异常处理:

通过抛出一个自定义的异常,可以终止forEach循环。在捕获到该异常后,程序会跳出forEach循环。

const arr = [1, 2, 3, 4, 5, 6, 7];

try {
  arr.forEach((element) => {
    console.log(element);
  
    if (element === 3) {
      throw 'TerminateException'; // 抛出自定义异常
    }
  });
} catch (e) {
  if (e !== 'TerminateException') {
    throw e; // 抛出其他异常
  }
}

3.使用for...of循环:

如果只需要在特定条件下终止循环,可以考虑使用for...of循环代替forEach循环。for...of循环支持break语句来终止循环。

const arr = [1, 2, 3, 4, 5, 6, 7];

for (const item of arr) {
  console.log(item);
  
  if (item === 4) {
    break; // 终止循环
  }
}

4.将数组长度设置成0

const array = [ 1, 2, 3, 4, 5, 6, 7 ]

array.forEach((item) => {
  if (item >= 4) {
    console.log(item) // 输出:4
    array.length = 0
  }
})

5.建议使用for循环和some方法

const arr = [1, 2, 3, 4, 5, 6, 7]

for (let i = 0, len = arr.length; i < len; i++) {
  if (arr[ i ] >= 4) {
    console.log(arr[ i ]) // 4
    break // return
  }
}

6.双层for循环跳出循环

// 双层for循环跳出循环 =>
for (let index = 0; index < 10; index++) {
    console.log('----🚀----', '第一个循环');
    let flag = false;
    for (let ind = 0; ind < 10; ind++) {
        console.log('----🚀----', '第二个循环', index, ind);
        if(index * ind > 20) {
            console.log('----🚀----', '跳出循环');
            flag = true;
            break;
        }
    }
    if(flag) {
        break
    }
}

outer: for (let index = 0; index < 10; index++) {
    console.log('----🚀----', '第一个循环');
    for (let ind = 0; ind < 10; ind++) {
        console.log('----🚀----', '第二个循环', index, ind);
        if(index * ind > 20) {
            console.log('----🚀----', '跳出循环');
            break outer; // 这个是跳出整个循环
            // return 这个是终止循环
        }
    }
}

 

【出处】:https://www.cnblogs.com/dreamtt/p/17808107.html

=======================================================================================

posted on   jack_Meng  阅读(1979)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
历史上的今天:
2019-01-08 Json字符串、Xml字符串转C#实体类Class
2018-01-08 C#机器学习插件 ---- AForge.NET
2018-01-08 人工智能----语音助手
2016-01-08 汇编题目:计算32位二进制的加法
2015-01-08 在WORD2007中添加修改组件

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

支付宝打赏

主题色彩