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

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

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


当前回答

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

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


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

其他回答

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

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
} 

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

以下是推荐的原因

假设我写

if(someVal)
    alert("True");

然后下一个开发人员说,“哦,我需要做一些其他的事情”,所以他们写了下来

if(someVal)
    alert("True");
    alert("AlsoTrue");

现在你可以看到"AlsoTrue"总是为真,因为第一个开发人员没有使用大括号。

javascript有很多问题。看看JavaScript架构师Douglas Crockford谈论的if语句似乎很好,但return语句可能会引入一个问题。

return
{
    ok:false;
}
//silent error (return undefined)

return{
    ok:true;
}
//works well in javascript

技术上没有,但是非常推荐!!

忘掉“这是个人偏好”、“代码会正常运行”、“它对我来说工作得很好”、“它更可读”之类的废话。如果你犯了一个错误,这很容易导致非常严重的问题,相信我,当你在编码时很容易犯错误(不相信吗?,看看著名的苹果go to fail漏洞)。

论据:“这是个人偏好”

不,不是的。除非你们是一个人去火星,不然不行。大多数时候会有其他人阅读/修改您的代码。在任何严肃的编码团队中,这都是被推荐的方式,所以这不是一个“个人偏好”。

参数:“代码将运行良好”

意面代码也是如此!这是否意味着可以创建它?

论据:“这对我来说很有效”

在我的职业生涯中,我见过很多因为这个问题而产生的bug。你可能不记得有多少次你注释掉了“DoSomething()”,并对为什么要调用“SomethingElse()”感到困惑:

if (condition) 
    DoSomething();
SomethingElse();

或者添加了'SomethingMore'并且没有注意到它将不会被调用(即使缩进暗示相反):

if (condition)
  DoSomething();
  SomethingMore();

这是我在现实生活中遇到的一个例子。有人想要关闭所有日志,所以他们运行find&replace "console.log" => //"console.log":

if (condition) 
   console.log("something");
SomethingElse();

看到问题了吗?

即使你认为,“这些都是微不足道的,我永远不会这么做”;记住,总会有一个团队成员的编程技能不如你(希望你不是团队中最差的!)

参数:“这更有可读性”

如果说我学过编程,那就是简单的事情很快就会变得非常复杂。这是很常见的:

if (condition) 
    DoSomething();

在使用不同的浏览器/环境/用例进行测试或添加新功能后,它会变成以下内容:

if (a != null)
   if (condition) 
      DoSomething();
   else
      DoSomethingElse(); 
      DoSomethingMore();
else 
    if (b == null)
         alert("error b");
    else 
         alert("error a");

和这个比较:

 if (a != null) {
    if (condition) { 
       DoSomething();
    }
    else {
       DoSomethingElse();
       DoSomethingMore();
    }
 } else if (b == null) {
    alert("error b");
 } else {
    alert("error a");
 }

PS:在上面的例子中注意到错误的人会得到加分。

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