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

查看:73
本文介绍了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.

是否有什么办法可以很好地将所有语句括在JavaScript的花括号中?

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天全站免登陆