不能在循环之外有中断(即使它在循环中!)
如果某个条件为真,我试图打破循环。我的代码工作正常,直到我尝试添加中断。运行时 VS2010 和 IE8 中的智能感知错误告诉我我无法在循环之外中断,但我不认为我是。
我完全困惑,所以希望有人能指出我忽略的一些明显的事情!
var value1 = "hello";
$.each(myJsonObject.SomeCollection, function () {
if (value1 == this.value2) {
alert("Found it!");
exitFlag = true;
}
if (exitFlag) break;
});
I'm trying to break out of a loop if a certain condition is true. My code works fine until I try and add the break in. The intellisense error in VS2010 and IE8 when running both tell me I cant break outside of a loop, but I don't think I am.
I'm totally confused so hoping someone can point out something obvious I'm overlooking!
var value1 = "hello";
$.each(myJsonObject.SomeCollection, function () {
if (value1 == this.value2) {
alert("Found it!");
exitFlag = true;
}
if (exitFlag) break;
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
jQuery 可能没有对
.each()
函数使用循环。也许返回 false 可能会起作用(在 Python 中确实如此):jQuery might not be using a loop for the
.each()
function. Maybe returningfalse
might work (in Python it does):只需
return false;
即可退出.each
循环。 来自文档:使用 jQuery
.each
迭代器与使用常规循环不同,因此此处不能使用break
。就像这样做,这是不可能的:Simply
return false;
to exit the.each
loop. From the documentation:Using the jQuery
.each
iterator is not the same as using a regular loop, sobreak
cannot be used here. It would be like doing this, which is impossible:如果你的集合可以像数组一样被处理、导航和索引,那么只需使用常规循环并从中中断即可。或者,如果您执意使用
$.each
迭代器来完成如此简单的事情,那么只需让您的函数返回 false (这将有效地使$.each
迭代器停止)。为了重申我刚才所说的,如果该集合可以视为数组,则只需使用普通循环即可。除非您有充分的理由不这样做,否则请始终使用最简单、最干净的工具来完成工作。
If your collection can be treated, navigated and indexed like an array, just use a regular loop and break from it. Or if you are so bent in using the
$.each
iterator for such a simple thing, then just have your function return false (which will effectively make the$.each
iterator stop).And to re-enforce what I just said, if that collection can be treated as an array, just use a plain loop. Unless you have a good reason to do otherwise, always use the simplest, cleanest tool to get the job done.