How to break out of map or foreach loop

forEach() and map() are methods for looping arrays provided by the Array array object.
You cannot use break, 'continue' , etc. to end loop statements like js loop expressions .

So how to terminate the loop and jump out of this loop in the forEach() and map() methods?

break out of local loop

The return used in the foreach and map functions is used to jump out of this loop. Take the foreach loop as an example:

var arr = [1,2,3];
    var newArr = []
    arr.forEach((item,index) =>{
    
    
        //下标小于2时,直接return之后,不执行后面的push。
           if(index<2) {
    
    
            return item
        }
        newArr.push(item)
    })
    console.log(newArr)  // [3] //结果只有3

terminate loop

The throw used in the foreach and map functions throws an exception to jump out of this loop (forced exit, not recommended unless necessary). Take the foreach loop as an example:

var arr = [1,2,3]
var newArr = []
arr.forEach((item,index)=>{
    
    
    try{
    
    
        if(index > 1) {
    
    
            throw new Error('文本小于2')
        }
        newArr.push(item)
    }catch (e){
    
    
        // throw e
    }
})
console.log(newArr) [1,2]

Guess you like

Origin blog.csdn.net/weixin_49549509/article/details/128957069