标签如何与不是循环的语句一起使用? [英] How are labels used with statements that are not a loop?

查看:82
本文介绍了标签如何与不是循环的语句一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 ECMAScript 5.1规范 ,第12.12节,任何陈述都可以贴上标签 - 在简短的测试中,我的浏览器在任何陈述之前接受了一个标签。该规范还声明标签仅与 break continue 语句一起使用,并且快速测试显示这些语句抛出如果他们引用的标签没有引用包含它们的循环,则会出现未定义标签错误。

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.

所以我的问题是:什么是不是语句的标签循环用于?是否有一些上下文 break continue 可以引用一个不是循环的标签?

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?

推荐答案

显然,break和continue语句可以在任何语句中使用:

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");
}

调用show_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...)

这篇关于标签如何与不是循环的语句一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆