[英]Should I Ever Use Labels In Javascript? (If So, When?)
Backstory: Once again I was reading in my Javascript book and I bumped into something that the book didn't explain very well, and that I wasn't able to find any good examples of online. 背景故事:我再次读了我的Javascript书,碰到了本书无法很好解释的东西,而且我找不到任何好的在线示例。
Example from Book: 书中的示例:
parser:
while(token != null) {
// Code omitted here
}
The only paragraph used to explain this code said that by using a label I could refer to a statement elsewhere in my code and that labels are " commonly " used for loops. 唯一用来解释此代码的段落说,通过使用标签,我可以引用代码中其他地方的语句,并且标签“ 通常 ”用于循环。 I've never seen a label used before let alone "commonly."
我从未见过使用过的标签,更不用说“普通”了。
My question is: Are labels used and if so what is a good example of a place where I would want to use one? 我的问题是:是否使用了标签?如果是,我想在哪个地方使用标签?
The only time I've really seen it is in a nested loop or if statement you can use labels to break to a specific one for example: 我真正看到过的唯一一次是在嵌套循环中,或者是if语句,您可以使用标签将其打断为特定的标签,例如:
function foo ()
{
dance:
for(var k = 0; k < 4; k++){
for(var m = 0; m < 4; m++){
if(m == 2){
break dance;
}
}
}
}
the label "dance" lets you break to that point specifically if m == 2. 如果m == 2,则标签“ dance”可让您具体突破这一点。
In my experience I would not say they are very common. 以我的经验,我不会说它们很常见。
Example taken from here: How to break nested loops in javascript? 从此处获取的示例: 如何打破javascript中的嵌套循环?
Perhaps better example here: Best way to break from nested loops in Javascript? 也许是一个更好的例子: 摆脱Java嵌套循环的最佳方法? at the second answer.
在第二个答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.