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

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

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


当前回答

以下是推荐的原因

假设我写

if(someVal)
    alert("True");

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

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

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

其他回答

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

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

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

if(a===1) if(b===2) alert(a);
alert(b);

总是发现

if(valid) return;

对我的眼睛来说比

if(valid) {
  return;
}

还有条件的,比如

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

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

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

但我想这归结于编码风格

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

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"总是为真,因为第一个开发人员没有使用大括号。