开发者

Can't have break outside of loop (even though it is in a loop!)

开发者 https://www.devze.com 2023-02-20 03:20 出处:网络
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开发者_如何学Go in VS2010 and IE8 when running both tell m

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开发者_如何学Go 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;
});


jQuery might not be using a loop for the .each() function. Maybe returning false might work (in Python it does):

var value1 = "hello"; 

$.each(myJsonObject.SomeCollection, function () {

    if (value1 == this.value2) {
        alert("Found it!");
        exitFlag = true;
    }

    if (exitFlag) return false;
});


Simply return false; to exit the .each loop. From the documentation:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Using the jQuery .each iterator is not the same as using a regular loop, so break cannot be used here. It would be like doing this, which is impossible:

for (var i = 0; i < 10; ++i) {
  myFunc(i);
}

function myFunc(i) {
  if (i > 5) {
    break; // ILLEGAL
  }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消