如何停止Javascript forEach? [英] how to stop Javascript forEach?
问题描述
我正在使用nodejs和mongoose - 试图在深层注释中找到特定注释,并使用递归函数和foreach进行嵌套。有没有办法阻止nodejs forEach?据我所知,每个forEach迭代都是一个函数而且我不能只做休息,只能返回,但这不会停止foreach。
i'm playing with nodejs and mongoose — trying to find specific comment in deep comments nesting with recursive func and foreach within. Is there a way to stop nodejs forEach? As i understand every forEach iteration is a function and and i can't just do "break",only "return" but this won't stop foreach.
function recurs(comment){
comment.comments.forEach(function(elem){
recurs(elem);
//if(...) break;
});
}
推荐答案
你无法摆脱a forEach
。不过,我可以想到三种方法来伪造它。
You can't break from a forEach
. I can think of three ways to fake it, though.
1。丑陋的方式:将第二个参数传递给 forEach
到用作上下文,并在那里存储一个布尔值,然后使用 if
。这看起来很糟糕。
1. The Ugly Way: pass a second argument to forEach
to use as context, and store a boolean in there, then use an if
. This looks awful.
2。有争议的方式:在 try-catch
块中包围整个事件,并在想要中断时抛出异常。这看起来非常糟糕,并且可能会影响效果,但可以封装。
2. The Controversial Way: surround the whole thing in a try-catch
block and throw an exception when you want to break. This looks pretty bad and may affect performance, but can be encapsulated.
3。有趣的方式:使用 every()
。
['a', 'b', 'c'].every(function(element, index) {
// Do your thing, then:
if (you_want_to_break) return false
else return true
})
您可以使用 some()
,相反,如果你宁愿返回true
来打破。
You can use some()
instead, if you'd rather return true
to break.
这篇关于如何停止Javascript forEach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!