+ 1

Loop control with labels

How to use the labels with break and continue to control loops?

16th Mar 2017, 10:02 PM
Валерий Чкалов
Валерий Чкалов - avatar
2 Antworten
+ 11
Break statement terminates the loop directly. Continue statement tells the program to go to the top of the loop and iterate its contents again.
17th Mar 2017, 12:10 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
A label can be used with break and continue to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. outerloop: // This is the label name for (var i = 0; i < 5; i++) { document.write("Outerloop: " + i + "<br />"); innerloop: for (var j = 0; j < 5; j++) { if (j > 3 ) break ; // Quit the innermost loop if (i == 2) break innerloop; // Do the same thing if (i == 4) break outerloop; // Quit the outer loop document.write("Innerloop: " + j + " <br />"); } } document.write("Exiting the loop!<br /> "); Output: Entering the loop! Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 2 Outerloop: 3 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 4 Exiting the loop!
17th Mar 2017, 12:14 PM
Валерий Чкалов
Валерий Чкалов - avatar