我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
当前回答
以下是推荐的原因
假设我写
if(someVal)
alert("True");
然后下一个开发人员说,“哦,我需要做一些其他的事情”,所以他们写了下来
if(someVal)
alert("True");
alert("AlsoTrue");
现在你可以看到"AlsoTrue"总是为真,因为第一个开发人员没有使用大括号。
其他回答
除了@Josh K提到的原因(这也适用于Java, C等),JavaScript中的一个特殊问题是自动分号插入。维基百科的例子如下:
return
a + b;
// Returns undefined. Treated as:
// return;
// a + b;
因此,如果像这样使用,也可能会产生意想不到的结果:
if (x)
return
a + b;
写也没好到哪里去
if (x) {
return
a + b;
}
但也许这里的错误更容易检测(?)
在一行语句上使用花括号是没有编程理由的。
这只取决于程序员的偏好和可读性。
您的代码不会因此而崩溃。
我想指出的是,你也可以把花括号去掉else。正如约翰·瑞西格在这篇文章中看到的。
if(2 == 1){
if(1 == 2){
console.log("We will never get here")
}
} else
console.log("We will get here")
如果你这样做,请这样写:
if(a===1) if(b===2) alert(a);
alert(b);
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.