我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
当前回答
有一种方法可以实现多行非花括号if语句。(哇,多英语啊..)但是有点乏味:
if(true)
funcName();
else
return null;
function funcName(){
//Do Stuff Here...
}
其他回答
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
}
这种想法是这样的,如果你总是有括号,那么你就知道在这个块中插入其他语句。
有很多好的答案,所以我不会重复,除了说我的“规则”时,大括号可以省略:条件'返回'或'抛出'(例如)作为他们的唯一声明。在这种情况下,流控制已经清楚地表明它正在终止:
由于终止流控制,即使是“坏情况”也可以快速识别(并修复)。这个概念/结构“规则”也适用于许多语言。
if (x)
return y;
always();
当然,这也是为什么人们可能会使用linter..
这个问题问的是一行中的语句。然而,提供的许多示例说明了不要基于多行语句省略大括号的理由。在一行中不使用括号是完全安全的,如果这是您喜欢的编码风格的话。
例如,问题问这样做是否可以:
if (condition) statement;
它不会问这是否ok:
if (condition)
statement;
我认为去掉括号更可取,因为它使代码更具可读性,语法更少。
我的编码风格是永远不用括号,除非代码是一个块。不要在一行上使用多个语句(用分号分隔)。我发现这很容易阅读和清楚,从来没有“if”语句的范围问题。因此,在单个if条件语句上使用括号需要3行。是这样的:
if (condition) {
statement;
}
使用一行if语句更可取,因为它使用的垂直空间更少,代码更紧凑。
我不会强迫其他人使用这种方法,但它对我来说是有效的,我非常不同意所提供的关于省略括号如何导致编码/范围错误的例子。
不存在可维护性问题!
你们所有人的问题就是到处都用分号。多个语句不需要花括号。如果你想添加一个语句,只需使用逗号。
if (a > 1)
alert("foo"),
alert("bar"),
alert("lorem"),
alert("ipsum");
else
alert("blah");
这是有效的代码,将像您期望的那样运行!