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

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

        recurs(elem);

        //if(...) break;

    });
}

当前回答

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

其他回答

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

在某些情况下,数组。有些可能会满足要求。

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

数组中。forEach不能被打破,使用try…catch或hack方法,如Array。每个或数组。有些只会让你的代码更难理解。这个问题只有两种解决方案:

1)使用旧的for循环:这将是最兼容的解决方案,但当经常在大块代码中使用时,可能很难阅读:

var testArray = ['a', 'b', 'c'];
for (var key = 0; key < testArray.length; key++) {
    var value = testArray[key];
    console.log(key); // This is the key;
    console.log(value); // This is the value;
}

2) use the new ECMA6 (2015 specification) in cases where compatibility is not a problem. Note that even in 2016, only a few browsers and IDEs offer good support for this new specification. While this works for iterable objects (e.g. Arrays), if you want to use this on non-iterable objects, you will need to use the Object.entries method. This method is scarcely available as of June 18th 2016 and even Chrome requires a special flag to enable it: chrome://flags/#enable-javascript-harmony. For Arrays, you won't need all this but compatibility remains a problem:

var testArray = ['a', 'b', 'c'];
for (let [key, value] of testArray.entries()) {
    console.log(key); // This is the key;
    console.log(value); // This is the value;
}

3)很多人会同意第一种选择和第二种选择都不是好的候选人。在选项2成为新的标准之前,大多数流行的库(如AngularJS和jQuery)都提供了自己的循环方法,这些方法比JavaScript中的任何可用方法都要优越。对于那些还没有使用这些大型库并且正在寻找轻量级选项的人来说,可以使用像这样的解决方案,并且几乎与ECMA6相同,同时保持与旧浏览器的兼容性。

如果你重写Array方法,你可以从forEach循环中中断:

(function(){
    window.broken = false;

        Array.prototype.forEach = function(cb, thisArg) {
            var newCb = new Function("with({_break: function(){window.broken = true;}}){("+cb.replace(/break/g, "_break()")+"(arguments[0], arguments[1], arguments[2]));}");
            this.some(function(item, index, array){
                 newCb(item, index, array);
                 return window.broken;
            }, thisArg);
            window.broken = false;
        }

}())

例子:

[1,2,3].forEach("function(x){\
    if (x == 2) break;\
    console.log(x)\
}")

不幸的是,在这个解决方案中,你不能在回调中使用普通的break,你必须将无效代码包装在字符串中,本机函数不能直接工作(但你可以解决这个问题)

破坏快乐!