JavaScript中的'if'语句是否需要大括号? [英] Do 'if' statements in JavaScript require curly braces?
本文介绍了JavaScript中的'if'语句是否需要大括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对此几乎是肯定的,但我想确保避免错误的代码。在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?
if(foo)
bar;
这可以吗?
推荐答案
是的,它有效,但在'if'或'else'语句之后只有一行。如果需要使用多行,则需要花括号。
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(foo)
Dance with me;
else
Sing with me;
以下内容无法按照您希望的方式运行。
if(foo)
Dance with me;
Sing with me;
else
Sing with me;
You don't know anything;
但是,如果按照以下方式更正上述内容,那么它适用于您:
if(foo){
Dance with me;
Sing with me;
}else{
Sing with me;
You don't know anything;
}
这篇关于JavaScript中的'if'语句是否需要大括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文