中断forEach循环-trycatch理解

1,709 阅读2分钟

js中跳出循环的相关问题及理解

for循环

  • continue 跳出当前循环,==继续后续循环==
for(var i=0, len = arr.length ; i< len ; i++){
    if(i == 2){
        continue;
    }
    console.log(arr[i]);    
}
 
// q ,  w , r , t
  • break 中断循环,==后续循环不执行==

forEach循环中使用break会报错

function fun3(){
    let arr =[1,2,3,4]
    arr.forEach(ele=>{
        if(ele==2){
            break;
            // return
        }else{
            console.log(ele)
        }
    })
    console.log('结束')
}
fun3()
//22.html:73 Uncaught SyntaxError: Illegal break statement

forEach中使用return无法结束方法

function fun3(){
    let arr =[1,2,3,4]
    arr.forEach(ele=>{
        if(ele==2){
            // break;
            return
        }else{
            console.log(ele)
        }
    })
    console.log('结束')
}
fun3()
//1  3  4   结束

在forEach循环中,return 返回任何值,都只能退出当前循环。

要想跳出整个forEach循环,可以使用抛异常的方式:

try{
    arr.forEach(function(oo,index){
        if(index == 2){
             throw 'jumpout';
        }
        console.log(oo);
    });
}catch(e){
}
 
// q , w