JavaScript 中的“if"语句需要花括号吗? [英] Do 'if' statements in JavaScript require curly braces?
本文介绍了JavaScript 中的“if"语句需要花括号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
在 JavaScript 的一行语句中是否需要大括号?
我对此几乎持肯定态度,但我想确保避免错误代码.在 JavaScript 中,单个 if
语句是否需要花括号?
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屋!
查看全文