for use forEach and return, it is out of the current cycle, or the entire cycle

return must be used in the function inside

There are two return effect, the end of the function and returns the result

let aa = function() {
        for(var i = 0; i < 5; i++) {
            console.log(i)
            if (i == 3) {
                // return
                // break // 跳出整个循环
                // continue // 跳出当前循环
            }
        }
    }
    aa() // 0 1 2 3
 
    let bb = function () {
        let arr = [1, 2, 3, 4, 5]
        arr.forEach(item => {
            console.log(item)
            if (item == 3) {
                console.log('item')
                // return
                // break // 语法报错
                console.log('return')
            }
        })
    }
    bb() // 1 2 3 item 4 5

More results: for the use of return, break, is out of the whole cycle.

              forEach 使用return只是跳出了当前的循环, 使用break报语法错误。
              forEach  无法在所有元素都传递给调用的函数之前终止遍历

So how do you jump in forEach entire loop, you can use try, then take the initiative to throw an error:

 let bb = function () {
        let arr = [1, 2, 3, 4, 5]
        try {
            arr.forEach(item => {
                console.log(item)
                if (item == 3) {
                    console.log('item')
                    // return
                    // break // 语法报错
                    throw new error // 主动去抛出一个错误
                    console.log('return')
                }
            })
        } catch {
            console.log('跳出来了')
        }
    }
    bb() // 1 2 3 item 跳出来了

try/catch/finally

try statement allows us to define the code block error test at the time of execution

Code catch is, when an error is encountered try statement, executed

After finally is try and catch, regardless of whether an exception is executed

Transfer: https://blog.csdn.net/qq_42341025/article/details/99974038

let arr = [7,5,4,3,1,5,2,6,6,3,4]
arr.forEach((item,index) => {
    if(index === 3) {
        return    //不能终止循环
    }
})

It can also be used for instead of forEach

let arr = [7,5,4,3,1,5,2,6,6,3,4]
for(let i = 0; i < arr.length; i ++) {
    if(i === 3) {
        return    //可以终止循环
    }
}

Guess you like

Origin www.cnblogs.com/panghu123/p/11723644.html