我們都知道for循環里要跳出整個循環是使用break,但在數組中用forEach循環如要退出整個循環呢?使用break會報錯,使用return也不能跳出循環。
使用break將會報錯:
var arr = [1,2,3,4,5];
var num = 3;
arr.forEach(function(v){
if(v == num) {
break;
}
console.log(v);
});

使用return也不能跳出整個循環:
var arr = [1,2,3,4,5];
var num = 3;
arr.forEach(function(v){
if(v == num) {
return;
}
console.log(v);
});
解決方法:
1:使用try···catch捕獲異常實現:
try{
var array = [1,2,3,4,5];
array.forEach(( item,index ) => {
if(item == 3){
// 執行完 1 2 之后就報錯,就跳出循環了
throw new Error("ending");//報錯,就跳出循環
}else{
console.log(item);
}
})
}catch(e){
if(e.message == "ending"){
console.log("結束了") ;
}else{
console.log(e.message);
}
}

2:使用arr.some( ) 或者 arr.every( ) 替代
some()當內部return true時跳出整個循環:
var arr = [1,2,3,4,5];
var num = 3;
arr.some( item =>{
if( item == num ) {
return true;
}
console.log( item );
});
every()當內部return false時跳出整個循環:
var arr = [1,2,3,4,5];
var num = 3;
arr.every( item =>{
if( item == num ) {
return false;
}else{
console.log( item );
return true;
}
});