How are labels used with statements that are not a loop?

我们两清 提交于 2019-12-12 07:14:59

问题


According to the ECMAScript 5.1 spec, section 12.12, any statement can be labelled - and in a brief test my browser accepted a label before any statement. The spec also states that labels are used exclusively with break and continue statements, and a quick test revealed that those statements throw an "undefined label" error if the label they reference does not refer to a loop that contains them.

So my question is this: what are labels for statements that are not loops used for? Is there some context in which break or continue can reference a label that is not a loop?


回答1:


Apparently the break and continue statements can be used within any statement:

http://docstore.mik.ua/orelly/webprog/jscript/ch06_11.htm

In which case things like this become legal:

function show_alert()
{
    label:
    {
        break label;
        alert("Hello! I am an alert box!");
    }
    alert("hi");
}

When show_alert() is called, only the "hi" alert is shown.

As far as I know, this is the only use of the {} code blocks, other than for code styling. (there was a question on here about that, and noone could come up with anything other than readability, but I can't find it now...)




回答2:


Yes you can label any statement. You just need to put the statement in curly braces, i.e.

{start:var a=1;}

this will not show undefined label error.



来源:https://stackoverflow.com/questions/8783054/how-are-labels-used-with-statements-that-are-not-a-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!