码迷,mamicode.com
首页 > Web开发 > 详细

js 终止 forEach 循环

时间:2018-10-13 02:35:16      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:catch   array   UNC   异常   each   方式   cond   first   抛出异常   

1.因为 forEach() 无法通过正常流程终止,所以可以通过抛出异常的方式实现终止。

try{
  var array = ["first","second","third","fourth"];
  // 执行到第3次,结束循环
  array.forEach(function(item,index) {
    if(item == "third"){
      throw new Error("EndIterative");
    }

    console.log(item); // first second
  });
}catch(e){
  if(e.message != "EndIterative") throw e;
}
// 下面的代码不影响继续执行
console.log("继续执行。。。");

.

js 终止 forEach 循环

标签:catch   array   UNC   异常   each   方式   cond   first   抛出异常   

原文地址:https://www.cnblogs.com/crazycode2/p/9781169.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!