how to stop Javascript forEach?

This question already has an answer here:

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

  • You can't break from a forEach . I can think of three ways to fake it, though.

    1. The Ugly Way : pass a second argument to forEach to use as context, and store a boolean in there, then use an if . This looks awful.

    2. The Controversial Way : surround the whole thing in a try-catch block and throw an exception when you want to break. This looks pretty bad and may affect performance, but can be encapsulated.

    3. The Fun Way : use every() .

    ['a', 'b', 'c'].every(function(element, index) {
      // Do your thing, then:
      if (you_want_to_break) return false
      else return true
    })
    

    You can use some() instead, if you'd rather return true to break.


    Breaking out of Array#forEach is not possible. (You can inspect the source code that implements it in Firefox on the linked page, to confirm this.)

    Instead you should use a normal for loop:

    function recurs(comment) {
        for (var i = 0; i < comment.comments.length; ++i) {
            var subComment = comment.comments[i];
            recurs(subComment);
            if (...) {
                break;
            }
        }
    }
    

    (or, if you want to be a little more clever about it and comment.comments[i] is always an object:)

    function recurs(comment) {
        for (var i = 0, subComment; subComment = comment.comments[i]; ++i) {
            recurs(subComment);
            if (...) {
                break;
            }
        }
    }
    

    As others have pointed out, you can't cancel a forEach loop, but here's my solution:

    ary.forEach(function loop(){
        if(loop.stop){ return; }
    
        if(condition){ loop.stop = true; }
    });
    

    Of course this doesn't actually break the loop, it just prevents code execution on all the elements following the "break"

    链接地址: http://www.djcxy.com/p/70038.html

    上一篇: javascript数组映射方法中的break语句

    下一篇: 如何阻止Javascript forEach?