我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。

在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?

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


当前回答

我在一个类似的经历中找到了这个答案,所以我决定用我的经历来回答它。

无括号语句在大多数浏览器中都可以工作,然而,我测试了无括号方法实际上在某些浏览器中不起作用。

截至2018年2月26日,该声明在苍白的月亮,但不是谷歌Chrome。

function foo()
   return bar;

其他回答

No

但他们是被推荐的。如果你要展开你的陈述,你会需要它们。

这是完全有效的

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

然而,强烈建议您总是使用大括号,因为如果您(或其他人)展开语句,就会需要它。

在所有带有括号的C语法风格语言中都遵循同样的做法。C, c++, Java,甚至PHP都支持不带括号的一行语句。你必须意识到你只保存了两个角色,有些人的支撑风格甚至连一行都没有保存。我更喜欢全括号的风格(像下面这样),所以它往往有点长。这种权衡很好地满足了代码可读性非常清晰的事实。

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

在一行语句上使用花括号是没有编程理由的。

这只取决于程序员的偏好和可读性。

您的代码不会因此而崩溃。

No, curly braces are not necessary, However, one very important reason to use the curly brace syntax is that, without it, there are several debuggers that will not stop on the line inside the if statement. So it may be difficult to know whether the code inside the if statement ran without altering the code (some kind of logging/output statements). This is particularly a problem when using commas to add multiple lines of execution. Without adding specific logging, it may be difficult to see what actually ran, or where a particular problem is. My advice is to always use curly braces.

这是一个风格问题,但花括号有助于防止可能的悬空。

我在一个类似的经历中找到了这个答案,所以我决定用我的经历来回答它。

无括号语句在大多数浏览器中都可以工作,然而,我测试了无括号方法实际上在某些浏览器中不起作用。

截至2018年2月26日,该声明在苍白的月亮,但不是谷歌Chrome。

function foo()
   return bar;