how to stop Javascript forEach?

2022-08-29 23:09:21

I'm playing with Node.js and Mongoose — trying to find specific comment in deep comments nesting with recursive function and within. Is there a way to stop Node.js ? As I understand every iteration is a function and and I can't just do , only but this won't stop .forEachforEachforEachbreakreturnforEach

function recurs(comment) {
    comment.comments.forEach(function(elem) {

        recurs(elem);

        //if(...) break;

    });
}

答案 1

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

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

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

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 to break.return true


答案 2

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 loop:for

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 is always an object:)comment.comments[i]

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