基于哪个条件打破了 Javascript 中的 while 循环,最干净的分支方法是什么?
假设我有这个循环,
while(condition1 && condition2 && condition3 && condition4){
browseReddit();
}
if (!condition1){}
if (!condition2){}
if (!condition3){}
if (!condition4){}
它可能会被 4 个条件中的任何一个变为 false 所破坏,并且我想根据它是哪个条件来执行不同的代码。理想情况下,我不想对它们进行过多的评估。假设 browseReddit()
迫使我们再次评估它们。
我目前正在做的就是在循环后面放置一个 if 链。有更干净的方法吗?在你的回答中,简洁是最重要的。
Say I've got this loop
while(condition1 && condition2 && condition3 && condition4){
browseReddit();
}
if (!condition1){}
if (!condition2){}
if (!condition3){}
if (!condition4){}
It could be broken by any of the 4 conditions becoming false, and I would want to execute different code based on which one(s) it was. Ideally, I would not like to evaluate them all more than I absolutely have to. Assume browseReddit()
forces us to evaluate them all again.
Putting an if chain after the loop is how I'm doing it currently. Is there a cleaner way? value brevity above all else in your answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最终编辑:
jsfiddle: http://jsfiddle.net/ctrlfrk/HjftT/3/
Final edit:
jsfiddle: http://jsfiddle.net/ctrlfrk/HjftT/3/
我会采用您当前代码示例中的方式,这样您就不会免除测试所有四种退出情况。
I would go with the way you have in your current code sample, so that you don't exempt yourself from testing all four of your exit cases.