想要在满足指定条件的时候跳出forEach循环
但是在打包的时候出错如下:
查阅相关资料,发现无法终止forEach遍历,跳出循环
然而 for循环
可以通过 return和break跳出循环
所以改用for循环,成功得到想要的效果
扩展:
for循环如果是多层循环 可以将循环命名,跳出指定的循环。
-
first: //需要将循环命名
-
for( var i= 0;i< 10;i++){
-
for( var j= 0;j< 5;j++){
-
if(i== 3 && j== 4){
-
break first; //跳出循环first
-
}
-
}
-
}
forEach 如果要提前终止
需要将forEach()方法放在一个try块中,并能抛出一个异常。如果forEach()调用的函数抛出foreach.break异常,循环会提前终止:
-
var myerror = null;
-
try{
-
arr.forEach( function(el,index){
-
if (el== 20) {
-
console.log( "try中遇到20,能退出吗?"); //
-
foreach.break= new Error( "StopIteration");
-
} else{
-
console.log(el);
-
}
-
});
-
} catch(e){
-
console.log(e.message);
-
if(e.message=== "foreach is not defined") {
-
console.log( "跳出来了?"); //
-
return;
-
} else throw e;
-
} //可以跳出来
-