在 JavaScript 中使用标签是不好的做法吗?
我刚刚发现在 JavaScript 中使用 label ,例如:
for (var i in team) {
if(i === "something") {
break doThis: //Goto the label
} else {
doThat();
}
}
doThis: //Label
doIt();
我直到现在才听说过这个,而且我在网上找不到太多关于它的信息,我开始认为这是有原因的。
在我看来,这类似于其他语言中的 GOTO 语句,并且被认为是不好的做法。我的假设正确吗?
I just found out about using label s in JavaScript, such as:
for (var i in team) {
if(i === "something") {
break doThis: //Goto the label
} else {
doThat();
}
}
doThis: //Label
doIt();
I've not heard about this until now and I can't find much information online about it and I'm beginning to think there is a reason for that.
It seems to me like this is similar to a GOTO
statement in other languages and would be considered bad practice. Would I be right in assuming this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
JavaScript 中的标签主要与break一起使用,或者在嵌套循环中继续使用,以便能够中断外部循环,或者从内部循环内的代码继续外部循环:
如果您使用不带“外部”标签的继续,它将转到内循环的下一次迭代。这就是 Javascript 中需要标签的原因。
The labels in JavaScript are used mainly with break, or continue in nested loops to be able to break the outer, or continue the outer loop from the code inside inner loop:
If you used continue without 'outer' label, it would go to the next iteration of inner loop. That's why there is a need for labels in Javascript.
这些是循环断路器标识符。如果您有嵌套循环(循环内的循环)并使用这些标识符,您可以有条件地指定何时以及从哪个循环中断,它们非常有用。
Those are loop breaker identifiers. They are useful if you have nested loops (loops inside loops) and using these identifiers, you can conditionally specify when and which loop to break out from.
2020年编辑,
根据MDN:
我2015年的回答:
https://developer.mozilla.org/en-US /docs/Web/JavaScript/Reference/Statements/label
2020 edit,
according to MDN:
My 2015 answer:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
带标签的中断可以打破任何代码块,而不仅仅是循环
结果:
测试1通过
测试2通过
测试3通过
labelled breaks can break out of any block of code not just loops
result:
test 1 passed
test 2 passed
test 3 passed
有一种解决方法可以使用 while 循环代替内部 for 循环,以获得更好的可读性。
There is a workaround to use while loops instead of inner for loops for better readability.