[英]What is the use case for “break Identifier” in JavaScript?
BreakStatement : break ; break [no LineTerminator here] Identifier ;
then it goes 然后它去了
The program contains a break statement with the optional Identifier, where Identifier does not appear in the label set of an enclosing (but not crossing function boundaries) Statement.
该程序包含带有可选标识符的break语句,其中Identifier不出现在封闭(但不跨越函数边界)Statement的标签集中。
...
...
A BreakStatement with an Identifier is evaluated as follows:
具有标识符的BreakStatement的计算方法如下:
Return (break, empty, Identifier).
What on bloody earth does this mean? 这对血腥地球意味着什么?
A label is something like this: 标签是这样的:
// ...
mylabel:
// ...
This can be placed anywhere as a statement. 这可以放在任何地方作为声明。
It is useful to break
/ continue
when having multiple nested for
loops. 当有多个嵌套
for
循环时, break
/ continue
是很有用的。
An example of its usage: 其用法示例:
var i, j;
loop1:
for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1"
loop2:
for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2"
if (i === 1 && j === 1) {
continue loop1;
}
console.log("i = " + i + ", j = " + j);
}
}
// Output is:
// "i = 0, j = 0"
// "i = 0, j = 1"
// "i = 0, j = 2"
// "i = 1, j = 0"
// "i = 2, j = 0"
// "i = 2, j = 1"
// "i = 2, j = 2"
// Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2"
If you look on MDN , there's examples 如果你看一下MDN ,就有例子
outer_block: {
inner_block: {
console.log('1');
break outer_block; // breaks out of both inner_block and outer_block
console.log(':-('); // skipped
}
console.log('2'); // skipped
}
as you can see, you can break
with an identifier that selects a label higher up in the chain than just the first immediate parent statement. 正如您所看到的,您可以使用标识符来
break
,该标识符选择链中较高的标签而不仅仅是第一个直接父语句。
The default action without an identifier would be 没有标识符的默认操作是
outer_block: {
inner_block: {
console.log('1');
break; // breaks out of the inner_block only
console.log(':-('); // skipped
}
console.log('2'); // still executed, does not break
}
The break has to be inside the label, you can't break labels based on indentifiers that the break is outside of. 中断必须在标签内,您不能根据断点超出的标识符来破坏标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.