JavaScript 中的“if”语句需要花括号吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7117873/
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
Do 'if' statements in JavaScript require curly braces?
提问by rubixibuc
Possible Duplicate:
Are curly braces necessary in one line statements in JavaScript?
I am almost positive of this, but I want to make sure to avoid faulty code. In JavaScript do single if
statements need curly braces?
我对此几乎持肯定态度,但我想确保避免错误代码。在 JavaScript 中,单个if
语句需要花括号吗?
if(foo)
bar;
Is this OK?
这个可以吗?
回答by OM The Eternity
Yes, it works, but only up to a single line just after an 'if' or 'else' statement. If multiple lines are required to be used then curly braces are necessary.
是的,它可以工作,但只能在“if”或“else”语句之后最多一行。如果需要使用多行,则需要大括号。
The following will work
以下将起作用
if(foo)
Dance with me;
else
Sing with me;
The following will NOT work the way you want it to work.
以下内容不会按照您希望的方式工作。
if(foo)
Dance with me;
Sing with me;
else
Sing with me;
You don't know anything;
But if the above is corrected as in the below given way, then it works for you:
但是,如果按照以下给出的方式更正上述内容,那么它对您有用:
if(foo){
Dance with me;
Sing with me;
}else{
Sing with me;
You don't know anything;
}
回答by user123444555621
While it's syntactically okay to omit them, you shouldn't. The one case where ambiguity strikes hard is
虽然省略它们在语法上是可以的,但您不应该这样做。歧义严重的一种情况是
if (false)
if (true) foo();
else
bar();
This will run neither foo
nor bar
since the else
belongs to the second if
statement. No problem if braces are used:
这既foo
不会运行,也不会运行,bar
因为else
属于第二个if
语句。如果使用大括号没问题:
if (false) {
if (true) { foo(); }
} else {
bar();
}
回答by Naveed
Yes it is allowed. It is also discussed before:
是的,这是允许的。之前也讨论过:
But it should be avoided:
但应该避免:
回答by Tomalak
Yes, it's syntactically valid. But it is considered bad style.
是的,它在语法上是有效的。但它被认为是不好的风格。
If you wrote it on a single line, you couldargue that there are situations where it's okay, because it is unambiguous.
如果你把它写在一行上,你可能会争辩说在某些情况下它是可以的,因为它是明确的。
if (foo) bar;
In most cases though, using curly brackets adds to code clarity, which is a good thing. Code is more often read than written, and it should be as unambiguous as possible.
但在大多数情况下,使用大括号会增加代码的清晰度,这是一件好事。代码的阅读次数多于编写次数,因此代码应尽可能明确。
Also, if you at some point need to add a second statement, you will most definitely need curlies anyway.
此外,如果您在某个时候需要添加第二个语句,无论如何您肯定需要卷曲。