js 終止 forEach 循環


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("繼續執行。。。");

.


免責聲明!

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



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