JavaScript 中的单行语句需要大括号吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4797286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are braces necessary in one-line statements in JavaScript?
提问by Tower
I once heard that leaving the curly braces in one-line statements could be harmful in JavaScript. I don't remember the reasoning anymore and a Google search did not help much.
我曾经听说在单行语句中保留大括号在 JavaScript 中可能是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
Is there anything that makes it a good idea to surround all statements within curly braces in JavaScript?
在 JavaScript 中,将所有语句括在花括号内是否是一个好主意?
I am asking, because everyone seems to do so.
我问,因为每个人似乎都这样做。
回答by Josh K
No
不
But they are recommended. If you ever expand the statement you will need them.
但他们被推荐。如果您扩展该语句,您将需要它们。
This is perfectly valid
这是完全有效的
if (cond)
alert("Condition met!")
else
alert("Condition not met!")
However it is highly recommended that you always use braces because if you (or someone else) ever expands the statement it will be required.
但是,强烈建议您始终使用大括号,因为如果您(或其他人)曾经扩展该语句,则将需要它。
This same practice follows in all C syntax style languages with bracing. C, C++, Java, even PHP all support one line statement without braces. You have to realize that you are only saving two charactersand with some people's bracing styles you aren't even saving a line. I prefer a full brace style (like follows) so it tends to be a bit longer. The tradeoff is met very well with the fact you have extremely clear code readability.
在所有带有支撑的 C 语法风格语言中都遵循同样的做法。C、C++、Java,甚至 PHP 都支持没有大括号的一行语句。您必须意识到您只保存了两个字符,而对于某些人的支撑样式,您甚至没有保存一行。我更喜欢完整的支撑样式(如下所示),因此它往往会更长一些。由于您具有非常清晰的代码可读性,因此可以很好地进行权衡。
if (cond)
{
alert("Condition met!")
}
else
{
alert("Condition not met!")
}
回答by Rudu
There's a readability aspect - in that when you have compound statements it can get very confusing. Indenting helps but doesn't mean anything to the compiler/interpreter.
有一个可读性方面 - 当你有复合语句时,它会变得非常混乱。缩进有帮助,但对编译器/解释器没有任何意义。
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
And then there's an extensibility aspect:
然后是可扩展性方面:
//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
}
The thinking goes that if you always have the brackets then you know to insert other statements inside that block.
想法是,如果您总是有括号,那么您就知道在该块中插入其他语句。
回答by peawormsworth
The question asks about statements on one line. Yet, the many examples provided show reasons not to leave out braces based on multiple line statements. It is completely safe to not use brackets on one line, if that is the coding style you prefer.
该问题询问有关一行的陈述。然而,提供的许多示例显示了不基于多行语句省略大括号的原因。如果那是您喜欢的编码风格,那么在一行上不使用括号是完全安全的。
For example, the question asks if this is ok:
例如,问题询问这是否可以:
if (condition) statement;
It does not ask if this is ok:
它不会询问这是否可以:
if (condition)
statement;
I think leaving brackets out is preferable because it makes the code more readable with less superfluous syntax.
我认为去掉括号更可取,因为它使代码更具可读性,而且多余的语法更少。
My coding style is to never use brackets unless the code is a block. And to never use multiple statements on a single line (separated by semicolons). I find this easy to read and clear and never have scoping issues on 'if' statements. As a result, using brackets on a single if condition statement would require 3 lines. Like this:
我的编码风格是永远不要使用括号,除非代码是一个块。并且永远不要在一行中使用多个语句(用分号分隔)。我发现这很容易阅读和清晰,而且从来没有关于“if”语句的范围问题。因此,在单个 if 条件语句上使用括号需要 3 行。像这样:
if (condition) {
statement;
}
Using a one line if statement is preferable because it uses less vertical space and the code is more compact.
最好使用一行 if 语句,因为它使用较少的垂直空间并且代码更紧凑。
I wouldn't force others to use this method, but it works for me and I could not disagree more with the examples provided on how leaving out brackets leads to coding/scoping errors.
我不会强迫其他人使用这种方法,但它对我有用,而且我对所提供的关于省略括号如何导致编码/范围界定错误的示例完全不同意。
回答by Caner
Technically no but otherwise absolutely Yes!!!
技术上没有,但在其他方面绝对是的!!!
Forget about "It's personal preference","the code will run just fine","it has been working fine for me","it's more readable" yada yada BS. This could easily lead to very serious problems if you make a mistake and believe me it is very easy to make a mistake when you are coding(Don't belive?, check out the famous Apple go to fail bug).
忘记“这是个人喜好”,“代码运行良好”,“它对我来说一直很好”,“它更具可读性” yada yada BS。如果您犯了错误并且相信我,这很容易导致非常严重的问题,并且相信我在编码时很容易犯错误(不相信?,请查看著名的Apple go to fail 错误)。
Argument: "It's personal preference"
论点:“这是个人喜好”
No it is not. Unless you are a one man team leaving on mars, no. Most of the time there will be other people reading/modifying your code. In any serious coding team this will be the recommended way, so it is not a 'personal preference'.
不它不是。除非你是一个离开火星的单人团队,否则不会。大多数时候会有其他人阅读/修改您的代码。在任何认真的编码团队中,这将是推荐的方式,因此它不是“个人偏好”。
Argument: "the code will run just fine"
参数:“代码会运行得很好”
So does the spaghetti code! Does it mean it's ok to create it?
意大利面代码也是如此!这是否意味着可以创建它?
Argument: "it has been working fine for me"
论点:“它对我来说一直很好”
In my career I have seen so many bugs created because of this problem. You probably don't remember how many times you commented out 'DoSomething()'
and baffled by why 'SomethingElse()'
is called:
在我的职业生涯中,我见过很多因为这个问题而产生的错误。您可能不记得有多少次注释掉'DoSomething()'
并为为什么'SomethingElse()'
被调用感到困惑:
if (condition)
DoSomething();
SomethingElse();
Or added 'SomethingMore' and didn't notice it won't be called(even though the indentation implies otherwise):
或者添加了 'SomethingMore' 并且没有注意到它不会被调用(即使缩进暗示了其他情况):
if (condition)
DoSomething();
SomethingMore();
Here is a real life example I had. Someone wanted to turn of all the logging so they run find&replace "console.log"
=> //"console.log"
:
这是我遇到的一个现实生活中的例子。有人想关闭所有日志记录,所以他们运行 find&replace "console.log"
=> //"console.log"
:
if (condition)
console.log("something");
SomethingElse();
See the problem?
看到问题了吗?
Even if you think, "these are so trivial, I would never do that"; remember that there will always be a team member with inferior programming skills than you(hopefully you are not the worst in the team!)
即使你认为,“这些都是微不足道的,我永远不会那样做”;记住,总会有一个团队成员的编程能力比你差(希望你不是团队中最差的!)
Argument: "it's more readable"
论点:“它更具可读性”
If I've learned anything about programming, it is that the simple things become very complex very quickly. It is very common that this:
如果我学到了任何关于编程的知识,那就是简单的事情很快就会变得非常复杂。这是很常见的:
if (condition)
DoSomething();
turns into the following after it has been tested with different browsers/environments/use cases or new features are added:
在使用不同的浏览器/环境/用例进行测试或添加新功能后,变为以下内容:
if (a != null)
if (condition)
DoSomething();
else
DoSomethingElse();
DoSomethingMore();
else
if (b == null)
alert("error b");
else
alert("error a");
And compare it with this:
并将其与此进行比较:
if (a != null) {
if (condition) {
DoSomething();
}
else {
DoSomethingElse();
DoSomethingMore();
}
} else if (b == null) {
alert("error b");
} else {
alert("error a");
}
PS: Bonus points go to who noticed the bug in the example above.
PS:奖励积分归于注意到上述示例中的错误的人。
回答by william malo
There is no maintainability problem!
不存在可维护性问题!
The problem with all of you is that you Put semicolons everywhere. You don't need curly braces for multiple statements. If you want to add a statement, just use commas.
你们所有人的问题是到处都放了分号。多个语句不需要花括号。如果要添加语句,只需使用逗号。
if (a > 1)
alert("foo"),
alert("bar"),
alert("lorem"),
alert("ipsum");
else
alert("blah");
This is valid code that will run like you expect!
这是将像您期望的那样运行的有效代码!
回答by Yahel
There is no programming reason to use the curly braces on one line statements.
在一行语句上使用花括号没有任何编程理由。
This only comes down to coders preferences and readability.
这仅归结于编码人员的偏好和可读性。
Your code won't break because of it.
您的代码不会因此而中断。
回答by Chris Lercher
In addition to the reason mentioned by @Josh K (which also applies to Java, C etc.), one special problem in JavaScript is automatic semicolon insertion. From the Wikipedia example:
除了@Josh K 提到的原因(这也适用于 Java、C 等),JavaScript 中的一个特殊问题是自动分号插入。从维基百科的例子:
return
a + b;
// Returns undefined. Treated as:
// return;
// a + b;
So, this may also yield unexpected results, if used like this:
因此,如果像这样使用,这也可能会产生意想不到的结果:
if (x)
return
a + b;
It's not really much better to write
写的真好不到哪里去
if (x) {
return
a + b;
}
but maybe here the error is a little bit easier to detect (?)
但也许这里的错误更容易检测(?)
回答by pault
It's a matter of style, but curly braces are good for preventing possible dangling else's.
这是一个风格问题,但花括号有利于防止其他人的.
回答by Amir Raminfar
Here is why it's recommended
这就是推荐的原因
Let's say I write
假设我写
if(someVal)
alert("True");
Then the next developer comes and says "Oh, I need to do something else", so they write
然后下一个开发人员来了,说“哦,我需要做点别的”,所以他们写
if(someVal)
alert("True");
alert("AlsoTrue");
Now as you can see "AlsoTrue" will always be true, because the first developer didn't use braces.
现在您可以看到“AlsoTrue”将始终为真,因为第一个开发人员没有使用大括号。
回答by B.F.
I'm currently working on a minifier. Even now I check it on two huge scripts. Experimentally I found out: You may remove the curly braces behind for,if,else,while,function* if the curly braces don't include ';','return','for','if','else','while','do','function'. Irrespective line breaks.
我目前正在研究一个缩小器。即使现在我检查了两个巨大的脚本。通过实验我发现:如果大括号不包含 ';','return','for','if','else', 你可以删除 for,if,else,while,function* 后面的大括号“同时”、“做”、“功能”。不考虑换行。
function a(b){if(c){d}else{e}} //ok
function a(b){if(c)d;else e} //ok
Of course you need to replace the closing brace with a semicolon if it's not followed by on other closing brace.
当然,如果其他右括号后面没有跟着分号,则需要用分号替换右括号。
A function must not end in a comma.
函数不能以逗号结尾。
var a,b=function()c; //ok *but not in Chrome
var b=function()c,a; //error
Tested on Chrome and FF.
在 Chrome 和 FF 上测试。