return无法跳出forEach的循环

2018-07-30  本文已影响0人  Echo_前端

一次项目中使用forEach进行遍历,达到某一条件,希望跳出循环,代码不继续执行。

this.itemTableData.forEach(

    function(item, index){

        if (item.taskValue ==100) 

            { return }

经查询资料,得知forEach遍历并不能被终止,会被继续执行。

因此要达到所需效果,可以使用for循环,然后就可以使用break,continue,或者return跳出遍历。

另一个例子  return在forEach()中相当于continue在for循环中的用法,可以跳出单次循环,接着执行下一次循环

并且forEach的函数里面是不可以使用continue和break的,会报错  因为这是个函数,continue和break只能用于for循环

let arr = [1,2,3,4]

        arr.forEach(

            function(item,index){

                if(item == 3){

                    return

                }arr[index]= item+10

            }

        )

        console.log(arr)

上一篇 下一篇

猜你喜欢

热点阅读