首页 > Web开发 > 详细

JS中forEach跳出本次循环和终止循环

时间:2020-11-27 11:53:19      阅读:41      评论:0      收藏:0      [点我收藏+]

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

JS中forEach跳出本次循环和终止循环

原文:https://www.cnblogs.com/linqing001/p/14046870.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!