JavaScript if 语句
JavaScript 的 if 语句
使用 JavaScript 的 if 语句,当条件为真时,执行一段代码块。
语法
if (condition) {
// 如果条件为真,则要执行的代码块
}
请注意,if 是小写字母。大写字母(If 或 IF)会导致 JavaScript 错误。
示例
如果时间在18:00之前,请说"Good day":
if (hour< 18) {
greeting = "Good day";
}
The result of greeting will be:
示例
let age = 18;
let text = "You can Not drive";
if (age >= 18) {
text = "You can drive");
}
亲自试一试 »
let age = 16;
let text = "You can Not drive";
if (age >= 18) {
text = "You can drive");
}
亲自试一试 »嵌套 if
您可以在一个 if 语句中嵌套另一个 if 语句:
示例
let age = 16;
let country = "USA";
let text = "You can Not drive!";
if (country == "USA") {
if (age >= 16) {
text = "You can drive!";
}
}
亲自试一试 »嵌套的 if 语句会使你的代码更复杂。
更好的解决方案是使用逻辑 AND 运算符。
示例
let age = 16;
let country = "USA";
let text = "You can Not drive!";
if (country == "USA" && age >= 16) {
text = "You can drive!";
}
亲自试一试 »