欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

跳出循环的遍历

最编程 2024-03-05 10:25:39
...
  1. map不能跳出循环,
  2. forEach跳出本次循环
    使用return终止本次循环,执行下一次循环
let arr = [1, 2, 3];
arr.forEach((item, index) => {
    if(item === 2) {
        console.log('中止本次循环,继续执行下一次循环')
        return false;
    }
    console.log(index)
})
console.log('结束')
  1. forEach终止循环
    因为forEach无法通过正常流程结束循环,可以通过抛出异常的方式实现终止循环
let arr = [1, 2, 3];
try {
    arr.forEach((item, index) => {
        if(item === 2) {
            throw new Error('End')
        }
        console.log(index)
    })
} catch(e) {
    if(e.message === 'End') throw e;
}

下表是JS中常用的实现循环遍历的方法的跳出/结束遍历的办法:

方法 break continue return/return false return true
for 结束循环 跳出本次循环 不合法 不合法
forEach 不合法 不合法 跳出本次循环 跳出本次循环
for...in 结束循环 跳出本次循环 不合法 不合法
Array.map() 不合法 不合法 跳出本次循环 跳出本次循环
Array.some() 不合法 不合法 跳出本次循环 结束循序
Array.every() 不合法 不合法 结束循环 跳出本次循环
Array.filter() 不合法 不合法 跳出本次循环 跳出本次循环

参考链接
JS中如何跳出循环/结束遍历