forEach结束循环

 

//错误1
var a = [1,2]
a.forEach(v => {
    if(true){
        console.log(v) 
        return
    } 
    console.log("test")}
)
var b = 3
console.log(b)
//1
//2
//3    

 

 

//错误2
var a = [1,2]
a.forEach(v => {
    if(true){
        console.log(v) 
        break
    } 
    console.log("test")}
)
var b = 3
console.log(b)
//报错:Uncaught SyntaxError: Illegal break statement

 

 

//正确:try catch抛出异常
try {
    var a = [1,2]
    a.forEach(v => {
        if(true){
        console.log(v) 
        throw new Error('end')
    } 
    console.log("test")}
    )
    var b = 3
    console.log(b);
} catch( err ){
     console.log('err',err)
}    
//1
//err Error: end

 

上一篇:Js中foreach()用法及使用的坑


下一篇:Stream