独立的JavaScript块有什么用吗? [英] Do standalone JavaScript blocks have any use?

查看:66
本文介绍了独立的JavaScript块有什么用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于JavaScript块的 MDN文章给出以下示例:

The MDN article on JavaScript blocks gives this example:

var x = 1;
{
  var x = 2;
}
alert(x); // outputs 2

如您所见,JavaScript没有阻止范围.那么JavaScript中的独立块有没有很好的用例?

As you can see JavaScript doesn't have block scope. So are there any good use cases for standalone blocks in JavaScript?

独立"是指不与控制流语句(ifforwhile等)或function配对.

By "standalone" I mean not paired with a control flow statement (if, for, while, etc.) or a function.

推荐答案

简短的回答:...不是真的.

我对它们唯一了解的用途是标签:

Short answer: ...not really.

The only use I know for them is labels:

myBlock: {
    // stuff
    if (something) break myBlock // jump to end of block
    // more stuff
    if (somethingElse) continue myBlock // jump to beginning of block
    // blah blah blah, more stuff
}

(几乎像goto,更好的提防猛禽)

不用说,这是一个非常糟糕的主意.因此,基本上,什么都没有;只是不要使用它们.

Needless to say, this is a very bad idea. So basically, nothing; just don't use them.

(旁注:do { /* stuff */ if (something) break; /* stuff */ } while (false)可以做同样的事情)

(side note: a do { /* stuff */ if (something) break; /* stuff */ } while (false) could do the same thing)

这篇关于独立的JavaScript块有什么用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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