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

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

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


当前回答

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

....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以获得个性化的编码建议。如果编码头痛持续,请咨询医生。

其他回答

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

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

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

如果你这样做,请这样写:

if(a===1) if(b===2) alert(a);
alert(b);

除了@Josh K提到的原因(这也适用于Java, C等),JavaScript中的一个特殊问题是自动分号插入。维基百科的例子如下:

return
a + b;

// Returns undefined. Treated as:
//   return;
//   a + b;

因此,如果像这样使用,也可能会产生意想不到的结果:

if (x)
   return
   a + b;

写也没好到哪里去

if (x) {
   return
   a + b;
}

但也许这里的错误更容易检测(?)

这个问题问的是一行中的语句。然而,提供的许多示例说明了不要基于多行语句省略大括号的理由。在一行中不使用括号是完全安全的,如果这是您喜欢的编码风格的话。

例如,问题问这样做是否可以:

 if (condition) statement;

它不会问这是否ok:

 if (condition)
   statement;

我认为去掉括号更可取,因为它使代码更具可读性,语法更少。

我的编码风格是永远不用括号,除非代码是一个块。不要在一行上使用多个语句(用分号分隔)。我发现这很容易阅读和清楚,从来没有“if”语句的范围问题。因此,在单个if条件语句上使用括号需要3行。是这样的:

 if (condition) {
   statement;
 }

使用一行if语句更可取,因为它使用的垂直空间更少,代码更紧凑。

我不会强迫其他人使用这种方法,但它对我来说是有效的,我非常不同意所提供的关于省略括号如何导致编码/范围错误的例子。

不存在可维护性问题!

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

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

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