Preferred way to break a forEach method in JavaScript

This question already has an answer here:

  • How to short circuit Array.forEach like calling break? 24 answers

  • forEach is not supposed to break. If you 'd like to break a forEach -like loop, try every or some , which let you break out of the loop.

    A possible way to re-write your code could be

    var sum = 0;
    
    yourArray.some(function (item) {
        if (sum > 5) {
            return true;
        }
        sum += item;
    });
    

    You can't break out of a forEach . Just use a normal loop

    for(var i = 0; i < a; i++){
       sum += a[i];
       if(sum > 5) break;
    }
    

    Your current code seems a little silly.

    Your try/catch block is useless, as you don't ever throw an error for the catch block to catch, then re-throw (?) and you don't need to alert("break"); to stop a script.

    You can't break out of a forEach loop anyway, I think you'd just want to use a normal for loop:

    function sum(list){
      var sum = 0;
      for (var i = 0, len = list.length; i < len; i++){
        sum += list[i];
        if (sum > 5){
          break;
        }
      }
      return sum;
    }
    
    链接地址: http://www.djcxy.com/p/70048.html

    上一篇: 如何在JavaScript中打破foreach循环?

    下一篇: 在JavaScript中打破forEach方法的首选方法