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

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

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


当前回答

总是发现

if(valid) return;

对我的眼睛来说比

if(valid) {
  return;
}

还有条件的,比如

(valid) ? ifTrue() : ifFalse();

(我个人的观点)是否更容易阅读

if(valid) {
  ifTrue();
} else {
  ifFalse();
}

但我想这归结于编码风格

其他回答

语句的开始缩进级别应该等于它上面的开大括号的数量。(不包括引号或注释大括号或预处理器指令中的大括号)

否则,K&R将是很好的缩进样式。为了修复它们的风格,我建议在一行中放置简短的if语句。

if (foo) bar();    // I like this. It's also consistent with Python FWIW

而不是

if (foo)
   bar();   // not so good

如果我正在编写一个编辑器,我会让它的自动格式按钮将bar吸到与foo相同的行,并且如果你在bar之前按下return,我会让它在bar周围插入括号:

if (foo) {
  bar();    // better
}

然后,在if语句的主体中在bar的上方或下方添加新语句就很容易且一致了

if (foo) {
  bar();    // consistent
  baz();    // easy to read and maintain
}

有时他们似乎是需要的!我自己都不敢相信,但是昨天我在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...
}

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.