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

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

        recurs(elem);

        //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循环,但这是我的解决方案:

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

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

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

我们不用普通的回报吗?

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

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

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

我猜你想用array。prototype。find Find在数组中找到特定值时将自行中断。

var inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

function findCherries(fruit) { 
  return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); 
// { name: 'cherries', quantity: 5 }

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

例子:

var _ = require('lodash');

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

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