我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
当前回答
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.
其他回答
有一个可读性方面-当你有复合语句时,它可能会非常混乱。缩进有帮助,但对编译器/解释器没有任何意义。
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
}
这种想法是这样的,如果你总是有括号,那么你就知道在这个块中插入其他语句。
我在一个类似的经历中找到了这个答案,所以我决定用我的经历来回答它。
无括号语句在大多数浏览器中都可以工作,然而,我测试了无括号方法实际上在某些浏览器中不起作用。
截至2018年2月26日,该声明在苍白的月亮,但不是谷歌Chrome。
function foo()
return bar;
我想指出的是,你也可以把花括号去掉else。正如约翰·瑞西格在这篇文章中看到的。
if(2 == 1){
if(1 == 2){
console.log("We will never get here")
}
} else
console.log("We will get here")
有一种方法可以实现多行非花括号if语句。(哇,多英语啊..)但是有点乏味:
if(true)
funcName();
else
return null;
function funcName(){
//Do Stuff Here...
}
我目前正在做一个迷你器。即使是现在,我也要检查两个大脚本。通过实验,我发现: 如果花括号不包括';','return','for','if','else','while',' function',则可以删除后面的花括号。不考虑换行。
function a(b){if(c){d}else{e}} //ok
function a(b){if(c)d;else e} //ok
当然,如果后面没有其他的结束大括号,则需要用分号替换结束大括号。
函数不能以逗号结尾。
var a,b=function()c; //ok *but not in Chrome
var b=function()c,a; //error
在Chrome和FF上测试。