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

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

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


当前回答

我想指出的是,你也可以把花括号去掉else。正如约翰·瑞西格在这篇文章中看到的。

if(2 == 1){
    if(1 == 2){
        console.log("We will never get here")
    }
} else 
    console.log("We will get here")

其他回答

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.

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

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

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

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

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

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

以下是推荐的原因

假设我写

if(someVal)
    alert("True");

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

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

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

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

忘掉“这是个人偏好”、“代码会正常运行”、“它对我来说工作得很好”、“它更可读”之类的废话。如果你犯了一个错误,这很容易导致非常严重的问题,相信我,当你在编码时很容易犯错误(不相信吗?,看看著名的苹果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:在上面的例子中注意到错误的人会得到加分。