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

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

        recurs(elem);

        //if(...) break;

    });
}

当前回答

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

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

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

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

其他回答

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

例子:

var _ = require('lodash');

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

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

无法从Array#forEach中退出。(您可以在链接页面上查看在Firefox中实现它的源代码,以确认这一点。)

相反,你应该使用一个正常的for循环:

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

(或者,如果你想更聪明一点,comment.comments[i]总是一个对象:)

function recurs(comment) {
    for (var i = 0, subComment; subComment = comment.comments[i]; ++i) {
        recurs(subComment);
        if (...) {
            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; }
}

很丑,但很管用。

forEach不会在返回时中断,有一些丑陋的解决方案来完成这项工作,但我建议不要使用它,而是尝试使用Array.prototype.some或Array.prototype.every

Var ar = [1,2,3,4,5]; ar.some(函数(项目、索引){ If (item == 3){ 返回true; } Console.log ("item is:"+item+" index is:"+ index); });

下面的代码将在条件满足时中断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;