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

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

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


当前回答

有很多好的答案,所以我不会重复,除了说我的“规则”时,大括号可以省略:条件'返回'或'抛出'(例如)作为他们的唯一声明。在这种情况下,流控制已经清楚地表明它正在终止:

由于终止流控制,即使是“坏情况”也可以快速识别(并修复)。这个概念/结构“规则”也适用于许多语言。

if (x)
    return y;
    always();

当然,这也是为什么人们可能会使用linter..

其他回答

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

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

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

不存在可维护性问题!

你们所有人的问题就是到处都用分号。多个语句不需要花括号。如果你想添加一个语句,只需使用逗号。

if (a > 1)
 alert("foo"),
 alert("bar"),
 alert("lorem"),
 alert("ipsum");
else
 alert("blah");

这是有效的代码,将像您期望的那样运行!

大括号是不必要的.....但无论如何都要加进去

....why should you add braces in if statements if they are not necessary? Because there's a chance that it could cause confusion. If you're dealing with a project with multiple people, from different frameworks and languages, being explicit reduces the chances of errors cropping up by folks misreading each other's code. Coding is hard enough as it is without introducing confusion. But if you are the sole developer, and you prefer that coding style, then by all means, it is perfectly valid syntax.

作为一个普遍的哲学:避免写代码,但如果你必须写,那么让它明确。

if (true){console.log("always runs");}

if (true) console.log("always runs too, but what is to be gained from the ambiguity?");
    console.log("this always runs even though it is indented, but would you expect it to?")

^声明:这是个人观点-意见可能会有所不同。请咨询您的CTO以获得个性化的编码建议。如果编码头痛持续,请咨询医生。

有时他们似乎是需要的!我自己都不敢相信,但是昨天我在Firebug会议上(最近的Firefox 22.0)突然想到

if (! my.condition.key)
    do something;

执行do something,尽管my。condition。key为true。添加括号:

if (! my.condition.var) {
    do something;
}

解决了这个问题。有无数的例子表明,它显然可以在没有括号的情况下工作,但在这种情况下,它肯定没有。

倾向于在一行中放入多个语句的人当然应该总是使用大括号,因为

if (condition)
    do something; do something else;

很难找到。

有一种方法可以实现多行非花括号if语句。(哇,多英语啊..)但是有点乏味:

if(true)
   funcName();
else
   return null;


function funcName(){
  //Do Stuff Here...
}