JavaScript中的单行语句中是否需要花括号? [英] Are curly braces necessary in one-line statements in JavaScript?

查看:93
本文介绍了JavaScript中的单行语句中是否需要花括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经听说过将花括号留在单行语句中可能会对JavaScript造成伤害。我不再记得推理了,谷歌搜索也没多大帮助。是否有任何东西可以在JavaScript中用花括号括起所有语句?

I once heard that leaving the curly braces in one-line statements could be harmful in JavaScript. I don't remember the reasoning anymore and a Google search did not help much. Is there anything that makes it a good idea to surround all statements within curly braces in JavaScript?

我在问,因为每个人似乎都这样做。

I am asking, because everyone seems to do so.

推荐答案



但建议使用它们。如果你扩展声明,你将需要它们。

No

But they are recommended. If you ever expand the statement you will need them.

这是完全有效的

if (cond) 
    alert("Condition met!")
else
    alert("Condition not met!")

但强烈建议您始终使用大括号,因为如果您(或其他人)扩展了该语句,则需要使用大括号。

However it is highly recommended that you always use braces because if you (or someone else) ever expands the statement it will be required.

所有带有支撑的C语法风格语言都遵循同样的做法。 C,C ++,Java,甚至PHP都支持一行语句,没有大括号。你必须意识到你只保存两个字符,并且对于某些人的支撑样式,你甚至都没有保存一条线。我更喜欢全支撑式(如下),所以它往往会更长一点。由于您具有极其清晰的代码可读性,因此可以很好地满足权衡。

This same practice follows in all C syntax style languages with bracing. C, C++, Java, even PHP all support one line statement without braces. You have to realize that you are only saving two characters and with some people's bracing styles you aren't even saving a line. I prefer a full brace style (like follows) so it tends to be a bit longer. The tradeoff is met very well with the fact you have extremely clear code readability.

if (cond) 
{
    alert("Condition met!")
}
else
{
    alert("Condition not met!")
}

这篇关于JavaScript中的单行语句中是否需要花括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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