Question about loops and sequels

So, does this actually call the loop until nextLoop ? So, when he says continue nextLoop , does he immediately return to the top?

  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 this the nextLoop: loop designation? If so, what else can you name? Any links to why names might be useful?

+4
source share
4 answers

Yes. This is useful if you have a loop nested inside another loop and you want to continue the outer loop. Here is a page about MDC about it. So, in your case, in cycle i = 2 , if you say continue nextLoop from cycle j , it will jump out of cycle j , increment i and continue with i = 3 .

Using continue with shortcuts is usually not a good practice; this may indicate a need for reorganization of logic. But it acts perfectly syntactically, and I expect someone to ring with an example situation where they feel this is absolutely necessary.

Change Responding to your editing, nextLoop loop label (name) (without a colon): you can mark statements, and then use these labels as continue and break targets. See the specification for more details. A typical use is the label method in your example as well as continue or break , but note that break also applies to nested switch - you can mark them as loops and break them into an external one from one of the internal cases. You can even mix them so you can break the loop inside the switch (the label namespace is common to both).

+8
source

This is true. But you should avoid this. This is bad practice, similar to go to . Makes code difficult to read, understand, and spaghetti.

+1
source

Yes, this is the expected behavior. Look here

+1
source

other languages ​​allow you to break out of a selected number of inner loops if (! x) break 2; will continue the process at a point two steps up.

I have seen complex loops with multiple loop labels, and continue to call on a specific label, but I agree that this can be misleading logic.

You can almost always increase the efficiency of a cycle by writing it without continuing:

 var total= 0; nextLoop: for (var i = 0; i < 7; ++i ){ for (var j = 0; j < 6 ; ++j ){ if(i>4) total++; } total++; } total++; 
0
source

Source: https://habr.com/ru/post/1300893/


All Articles