js中跳出forEach循环

缘由近期在项目中使用lodash.js中的_.foreach方法处理数据,需要在满足条件时结束循环并不执行后面的js代码。

    因为foreach中默认没有break方法。在尝试中使用了return false;发现并不成功。

总结:

错误方法:return false;//仍然会执行完循环,但不再执行循环后面的js代码

_.forEach(tmArray, function (value, index, collection) {
   let temp = tmArray[index];
   _.forEach(tmArray, function (v2, index2, coll2) {
     if (index2 != index) {
     if (_.intersection(temp, tmArray[index2]).length > 0) {
     top.Dialog.alert("第" + (index + 1) + "条计划与第" + (index2 + 1) + "条计划周期有重叠,请重新设置!");
     return false;
   }
  }
 })
});

原因:foreach无法在循环结束前终止,return false只是结束了本次循环。

正确方法:因为foreach无法通过正常流程终止,可以通过抛出异常的方法,强行终止。

 1 try {
 2                         _.forEach(tmArray, function (value, index, collection) {
 3                             let temp = tmArray[index];
 4                             _.forEach(tmArray, function (v2, index2, coll2) {
 5                                 if (index2 != index) {
 6                                     if (_.intersection(temp, tmArray[index2]).length > 0) {
 7                                         top.Dialog.alert("第" + (index + 1) + "条计划与第" + (index2 + 1) + "条计划周期有重叠,请重新设置!");
 8                                         throw new Error("breakForEach");
 9                                         return false;
10                                     }
11                                 }
12                             })
13                         });
14                     } catch (e) {
15                         if (e.message!="breakForEach") throw e;
16                     }

猜你喜欢

转载自www.cnblogs.com/salmonLeeson/p/11321093.html