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    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM