A label in Javascript is an identifier. A label can have the same name as a variable. It is an independent syntax element (neither a variable nor a type). Its function is to identify the "labeled statement"
Label statement
Label can be declared before any statement or statement block, so that the statement or statement block is "labeled".
label1:
myFun1();
label2:{
var i = 1, j = 2;
var k = i j;
}
Note: when label ( label) is followed by multiple consecutive statements, only the first statement is labeled
Although GOTO is a reserved keyword in Javascript, there is no GOTO statement in it. In addition to GOTO, there are three other keywords in Javascript that can change the flow of the program: break, continue and return. Among them, break and continue can be used together with labels.
break and tags
break are usually used to break out of for, while loops and switch statements. By default, the break clause operates on the innermost loop statement, or the entire switch statement, so it does not have to specifically specify the scope of the break statement. But the break clause has an extended syntax to indicate its scope.
break my_label;
In addition to breaking out of loops and switch branches, you can also break out of labeled statements
var str = prompt('please input a string','1234567890');
my_label : {
if (str && str.length < 10) {
break my_label:
}
str = str.substr(str.length-10);
}
alert(str);
continue and label
continue are only meaningful for loop statements, so it can only work on for, for...in, while and do...while inside these statements. By default, it stops the current loop and jumps to the beginning of the next loop iteration.
continue can also be followed by a label (label), which indicates that it is terminated from within the loop body and continues to the label (label) instruction to start execution, and the statement indicated by this label must include this continue Loop statement.
For example:
loop:
for (var j = 0; j < 5; j )
{
if (j == 2) continue loop;
document.write("loop: " j );
}
The continue label in the above example does not reflect the special function of the label. In fact, the label can be removed and the effect will be the same. Let’s look at another example
document.write("Entering the loop!
");
outerloop: // This is the label name
for (var i = 0; i < 3; i )
{
document.write ("Outerloop: " i "
");
for (var j = 0; j < 5; j )
{
if (j == 3){
continue outerloop;
}
document.write("Innerloop: " j "
");
}
}
document.write("Exiting the loop!
");
Using the continue label to jump directly to the outer loop is the point.