Question about loops and continue
So is this actually naming the loop to nextLoop
? So when it says continue nextLoop
, does it go back to the top right awa开发者_开发技巧y?
var total = 0;
nextLoop:
for ( var i = 0; i < 7; ++i ) {
for ( var j = 0; j < 6 ; ++j ) {
if ( i < 5 )
continue nextLoop;
total++;
}
total++;
}
total++;
document.write( total );
Edit:
Is that naming the loop nextLoop:
? If so, what else can you name? Any references to why naming stuff can be useful?
Yes. This is useful for when you have a loop nested inside another loop and you want to continue the outer loop. Here's a page on MDC about it. So in your case, during the i = 2
loop if, from within the j
loop, you say continue nextLoop
, it'll jump out of the j
loop, do the i
increment, and continue with i = 3
.
Using continue
with labels is not usually good practice; it can indicate that the logic needs to be refactored. But it's perfectly valid syntactically and I expect someone will chime in with an example situation where they feel it's absolutely necessary.
Edit Answering your edit, the label (name) of the loop is nextLoop
(without the colon): You can label statements and then use those labels as the targets of continue
and break
. Check out the spec for details. The typical use is to label loops as in your example and either continue
or break
them, but note that break
also applies to nested switch
statements -- you can label them like loops and break to an outer one from within one of the inner one's cases. You can even intermix them so you can break a loop from within a switch (the label namespace is common to both).
It does. But you should avoid it. It is a bad practice, similar to go to
. Makes the code hard to read, understand and spaghetti like.
Yes, that is the expected behaviour. Take a look here
other languages let you break out of a selected number of inner loops, if(!x)break 2; would continue the process at a point two steps up.
I've seen complex loops with multiple loop labels, and continues called to a specific label, but I agree it can confuse the logic.
You can almost always improve the efficiency of a loop by writing it without the continue:
var total= 0;
nextLoop:
for (var i = 0; i < 7; ++i ){
for (var j = 0; j < 6 ; ++j ){
if(i>4) total++;
}
total++;
}
total++;
精彩评论