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

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

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


当前回答

有一个可读性方面-当你有复合语句时,它可能会非常混乱。缩进有帮助,但对编译器/解释器没有任何意义。

var a;
var b;
var c;

//Indenting is clear
if (a===true)
  alert(a); //Only on IF
alert(b); //Always

//Indenting is bad
if (a===true)
  alert(a); //Only on IF
  alert(b); //Always but expected?

//Nested indenting is clear
if (a===true)
  if (b===true)
    alert(a); //Only on if-if
alert (b); //Always

//Nested indenting is misleading
if (a===true)
  if (b===true)
    alert(a); //Only on if-if
  alert (b); //Always but expected as part of first if?

//Compound line is misleading
//b will always alert, but suggests it's part of if
if (a===true) alert(a);alert(b); 
else alert(c); //Error, else isn't attached

然后是可扩展性方面:

//Problematic
if (a===true)
  alert(a);
  alert(b); //We're assuming this will happen with the if but it'll happen always
else       //This else is not connected to an if anymore - error
  alert(c);

//Obvious
if (a===true) {
  alert(a); //on if
  alert(b); //on if
} else {
  alert(c); //on !if
} 

这种想法是这样的,如果你总是有括号,那么你就知道在这个块中插入其他语句。

其他回答

有一个可读性方面-当你有复合语句时,它可能会非常混乱。缩进有帮助,但对编译器/解释器没有任何意义。

var a;
var b;
var c;

//Indenting is clear
if (a===true)
  alert(a); //Only on IF
alert(b); //Always

//Indenting is bad
if (a===true)
  alert(a); //Only on IF
  alert(b); //Always but expected?

//Nested indenting is clear
if (a===true)
  if (b===true)
    alert(a); //Only on if-if
alert (b); //Always

//Nested indenting is misleading
if (a===true)
  if (b===true)
    alert(a); //Only on if-if
  alert (b); //Always but expected as part of first if?

//Compound line is misleading
//b will always alert, but suggests it's part of if
if (a===true) alert(a);alert(b); 
else alert(c); //Error, else isn't attached

然后是可扩展性方面:

//Problematic
if (a===true)
  alert(a);
  alert(b); //We're assuming this will happen with the if but it'll happen always
else       //This else is not connected to an if anymore - error
  alert(c);

//Obvious
if (a===true) {
  alert(a); //on if
  alert(b); //on if
} else {
  alert(c); //on !if
} 

这种想法是这样的,如果你总是有括号,那么你就知道在这个块中插入其他语句。

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!")
}

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

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;
}

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

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