美文网首页
return无法跳出forEach的循环

return无法跳出forEach的循环

作者: Echo_前端 | 来源:发表于2018-07-30 11:07 被阅读0次

一次项目中使用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)

相关文章

网友评论

      本文标题:return无法跳出forEach的循环

      本文链接:https://www.haomeiwen.com/subject/lstbmftx.html