1、forEach跳出本次循环
可使用return语句跳出本次循环,执行下一次循环
var arr = [1,2,3,4,5,6] arr.forEach((item) => { if (item === 3) { return } console.log(item) })
将输出 1 2 4 5 6,3不会输出
2、forEach终止循环
forEach无法通过正常流程(如break)终止循环,但可通过抛出异常的方式实现终止循环
var arr = [1,2,3,4,5,6] try{ arr.forEach((item) => { if (item === 3) { throw new Error('End Loop') } console.log(item) }) } catch (e) { if(e.message === 'End Loop') throw e }
将只输出 1 2
注意:在catch语句块中加了if(e.message === 'End Loop') throw e
这句代码会在控制台报一个错误,这个错误是try语句块中抛出的,如下:
new_file.html:24 Uncaught Error: End Loop at new_file.html:24 at Array.forEach () at new_file.html:22
如果不想看到这个报错,将if(e.message === 'End Loop') throw e
这一句删除就行
原文链接:https://blog.csdn.net/daoxiaofei/article/details/108690589