for 和 forEach 使用return,是跳出當前的循環,還是整個循環


return必須是使用在函數里面的

return有2個作用,結束函數和返回結果

let aa = function() {
        for(var i = 0; i < 5; i++) {
            console.log(i)
            if (i == 3) {
                // return
                // break // 跳出整個循環
                // continue // 跳出當前循環
            }
        }
    }
    使用return的情況: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')
            }
        })
    }
    使用return的情況:  bb() // 1 2 3 item 4 5

以上得出: for 使用return 、 break,是跳出了整個循環。

              forEach 使用return只是跳出了當前的循環, 使用break報語法錯誤。
              forEach  無法在所有元素都傳遞給調用的函數之前終止遍歷

那么如何在forEach 跳出整個循環,可以使用try ,然后主動拋出一個錯誤:

 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 語句允許我們定義 在執行的時候 進行錯誤測試的 代碼塊

catch 就是在try語句遇到錯誤的時候,所執行的代碼

finally 就是在 try 和catch之后 ,無論有無異常都執行

轉自: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    //不能終止循環
    }
})

也可以用for代替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    //可以終止循環
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM