我正在使用Node.js和Mongoose -试图在深层注释嵌套中找到特定的注释,其中带有递归函数和forEach。有没有办法停止Node.js forEach?正如我所理解的,forEach迭代都是一个函数,我不能只做break,只做return,但这不会停止forEach。

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

        recurs(elem);

        //if(...) break;

    });
}

当前回答

如果你不介意使用第三方库,你可以使用Lodash的forEach函数。

例子:

var _ = require('lodash');

_.forEach(comments, function (comment) {
    do_something_with(comment);

    if (...) {
        return false;     // Exits the loop.
    }
})

其他回答

下面的代码将在条件满足时中断foreach循环,下面是示例示例

    var array = [1,2,3,4,5];
    var newArray = array.slice(0,array.length);
    array.forEach(function(item,index){
        //your breaking condition goes here example checking for value 2
        if(item == 2){
            array.length = array.indexOf(item);
        }

    })
    array = newArray;

我们不用普通的回报吗?

function recurs(comment){
comment.comments.forEach(function(elem){
    recurs(elem);
    if(...) return;
});

它将从'recurs'函数返回。我这样使用它。虽然这不会从forEach中中断,而是从整个函数中中断,但在这个简单的示例中,它可能是有效的

正如其他人指出的那样,你不能取消forEach循环,但这是我的解决方案:

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

    if(condition){ loop.stop = true; }
});

当然,这实际上并没有打破循环,它只是阻止在“break”之后的所有元素上执行代码。

jQuery提供了一个each()方法,而不是forEach()方法。你可以通过返回false来突破每一个。forEach()是ECMA-262标准的一部分,据我所知,打破该标准的唯一方法是抛出异常。

function recurs(comment) {
  try {
    comment.comments.forEach(function(elem) {
      recurs(elem);
      if (...) throw "done";
    });
  } catch (e) { if (e != "done") throw e; }
}

很丑,但很管用。

如果你不介意使用第三方库,你可以使用Lodash的forEach函数。

例子:

var _ = require('lodash');

_.forEach(comments, function (comment) {
    do_something_with(comment);

    if (...) {
        return false;     // Exits the loop.
    }
})