我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
当前回答
不直接回答问题,但下面是关于一行中的if条件的简短语法
Ex:
var i=true;
if(i){
dosomething();
}
可以这样写:
var i=true;
i && dosomething();
其他回答
这是一个风格问题,但花括号有助于防止可能的悬空。
我想指出的是,你也可以把花括号去掉else。正如约翰·瑞西格在这篇文章中看到的。
if(2 == 1){
if(1 == 2){
console.log("We will never get here")
}
} else
console.log("We will get here")
有一个可读性方面-当你有复合语句时,它可能会非常混乱。缩进有帮助,但对编译器/解释器没有任何意义。
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
}
这种想法是这样的,如果你总是有括号,那么你就知道在这个块中插入其他语句。
有时他们似乎是需要的!我自己都不敢相信,但是昨天我在Firebug会议上(最近的Firefox 22.0)突然想到
if (! my.condition.key)
do something;
执行do something,尽管my。condition。key为true。添加括号:
if (! my.condition.var) {
do something;
}
解决了这个问题。有无数的例子表明,它显然可以在没有括号的情况下工作,但在这种情况下,它肯定没有。
倾向于在一行中放入多个语句的人当然应该总是使用大括号,因为
if (condition)
do something; do something else;
很难找到。
技术上没有,但是非常推荐!!
忘掉“这是个人偏好”、“代码会正常运行”、“它对我来说工作得很好”、“它更可读”之类的废话。如果你犯了一个错误,这很容易导致非常严重的问题,相信我,当你在编码时很容易犯错误(不相信吗?,看看著名的苹果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:在上面的例子中注意到错误的人会得到加分。