Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

javascript - 如何停止Javascript forEach? [重复](how to stop Javascript forEach? [duplicate])

This question already has an answer here:(这个问题在这里已有答案:)

Short circuit Array.forEach like calling break 28 answers(短路Array.forEach就像调用break 28的答案)

i'm playing with nodejs and mongoose — trying to find specific comment in deep comments nesting with recursive func and foreach within.(我正在玩nodejs和mongoose - 尝试在深层注释中找到特定注释,并使用递归函数和foreach进行嵌套。)

Is there a way to stop nodejs forEach?(有没有办法阻止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.(据我所知,每个forEach迭代都是一个函数而且我不能只做“休息”,只能“返回”,但这不会阻止foreach。) function recurs(comment){ comment.comments.forEach(function(elem){ recurs(elem); //if(...) break; }); }   ask by kulebyashik translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't break from a forEach .(你无法打破forEach 。)

I can think of three ways to fake it, though.(不过,我可以想到三种方法来伪造它。) 1. The Ugly Way : pass a second argument to forEach to use as context , and store a boolean in there, then use an if .(1. Ugly Way :将第二个参数传递给forEach用作上下文 ,并在其中存储一个布尔值,然后使用if 。) This looks awful.(这看起来很糟糕。) 2. The Controversial Way : surround the whole thing in a try-catch block and throw an exception when you want to break.(2.有争议的方式 :在try-catch块中包围整个事物,并在你想要破解时抛出异常。) This looks pretty bad and may affect performance , but can be encapsulated.(这看起来很糟糕, 可能会影响性能 ,但可以封装。) 3. The Fun Way : use every() .(3.有趣的方式 :使用every() 。) ['a', 'b', 'c'].every(function(element, index) { // Do your thing, then: if (you_want_to_break) return false else return true }) You can use some() instead, if you'd rather return true to break.(你可以使用some()代替,如果你宁愿return true来休息。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...