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

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

        recurs(elem);

        //if(...) break;

    });
}

当前回答

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); });

其他回答

我们不用普通的回报吗?

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

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

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; }
}

很丑,但很管用。

    var f = "how to stop Javascript forEach?".split(' ');
    f.forEach(function (a,b){
        console.info(b+1);
        if (a == 'stop') {
            console.warn("\tposition: \'stop\'["+(b+1)+"] \r\n\tall length: " + (f.length)); 
            f.length = 0; //<--!!!
        }
    });

无法从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;
        }
    }
}

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

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

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

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