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

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

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


当前回答

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语句。(哇,多英语啊..)但是有点乏味:

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


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

我在一个类似的经历中找到了这个答案,所以我决定用我的经历来回答它。

无括号语句在大多数浏览器中都可以工作,然而,我测试了无括号方法实际上在某些浏览器中不起作用。

截至2018年2月26日,该声明在苍白的月亮,但不是谷歌Chrome。

function foo()
   return bar;

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

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

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

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

以下是推荐的原因

假设我写

if(someVal)
    alert("True");

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

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

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