发现foreach时使用break或return无法跳出循环。经过查阅资料,发现两种方法可以跳出循环,在此记录
方法一:使用try{...}catch(e){...}
try{ var array = ["first","second","third","fourth"]; array.forEach(function(item,index){ if(item == "third"){ var a = aaaa;// first second 后就报错,就跳出循环了 throw new Error("ending");//报错,就跳出循环 }else{ console.log(item); } }) }catch(e){ if(e.message == "ending"){ console.log("结束了") ; }else{ console.log(e.message); } }
方法二:使用arr.some()或者arr.every()替代
some()当内部return true时跳出整个循环:
var arr = [1,2,3,4,5]; var num = 3; arr.some(function(v){ if(v == num) { return true; } console.log(v); });
every()当内部return false时跳出整个循环
var arr = [1,2,3,4,5]; var num = 3; arr.every(function(v){ if(v == num) { return false; }else{ console.log(v); return true; } });