You can label statements for later use with the following syntax:
label: statement
The following code adds a label for the for
loop.
var count = 10; start: for (var i=0; i < count; i++) { document.writeln(i); }
The break
statement breaks out of the loop,
forcing execution to continue with the next statement
after the loop.
var num = 0;
for (var i=1; i < 10; i++) {
if (i % 5 == 0) {
break;
}
num++;
}
console.log(num); //4
The code above generates the following result.
breaks to outer most loop
var num = 0;
outermost: /*ww w. java 2s . c o m*/
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
break outermost;
}
num++;
}
}
console.log(num); //55
The code above generates the following result.
The continue statement exits the current loop and continues from the top of the loop.
var num = 0;
for (var i=1; i < 10; i++) {
if (i % 5 == 0) {
continue;
}
num++;
}
console.log(num); //8
The code above generates the following result.
continue to outer most level:
var num = 0;
outermost: //from ww w. ja va2 s . c om
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
continue outermost;
}
num++;
}
}
console.log(num); //95
The code above generates the following result.