条件语句用于基于不同的条件来执行不同的动作。

条件语句
一般在写代码时,您总是需要为不同的决定来执行不同的动作。您可以在代码中使用条件语句来完成该任务。
在 JavaScript 中,我们可使用以下条件语句:
if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码
if...else 语句 - 当条件为 true 时执行代码,当条件为 false 时执行其他代码
if...else if....else 语句- 使用该语句来选择多个代码块之一来执行
switch 语句 - 使用该语句来选择多个代码块之一来执行
If 语句
只有当指定条件为 true 时,该语句才会执行代码。
语法
if (condition)
{
当条件为 true 时执行的代码
}
请使用小写的 if。使用大写字母(IF)会生成 JavaScript 错误!
实例
当时间小于 20:00 时,生成问候 "Good day":
if (time<20)
{
x="Good day";
}
<px 的结果是:
Good day

请注意,在这个语法中,没有 ..else..。您已经告知浏览器只有在指定条件为 true 时才执行代码。
If...else 语句
请使用 if....else 语句在条件为 true 时执行代码,在条件为 false 时执行其他代码。
语法
if (condition)
{
当条件为 true 时执行的代码
}
else
{
当条件不为 true 时执行的代码
}
实例
当时间小于 20:00 时,生成问候 "Good day",否则生成问候 "Good evening"。
if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
x 的结果是:
Good day

If...else if...else 语句
使用 if....else if...else 语句来选择多个代码块之一来执行。
语法
if (condition1)
{
当条件 1 为 true 时执行的代码
}
else if (condition2)
{
当条件 2 为 true 时执行的代码
}
else
{
当条件 1 和 条件 2 都不为 true 时执行的代码
}
实例
如果时间小于 10:00,则生成问候 "Good morning",如果时间大于 10:00 小于 20:00,则生成问候 "Good day",否则生成问候 "Good evening":
if (time<10)
{
x="Good morning";
}
else if (time>=10 && time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
x 的结果是:
Good morning
如您还有不清楚的可以在下面与我留言或是与我探讨QQ群308855039,我们一起飞!
¥11.00
steam 坚守国家战争 Holdfast: Nations At War 动作独立大型多人在线历史类游戏 PC中文正版国区激活码CDKey
¥6.80
PC中文Steam 古剑奇谭一Gujian 古剑奇谭1 古剑奇谭1古剑1 国区全球CDK激活码
¥8.80
doom永恒doom毁灭战士永恒毁灭战士永恒steam毁灭战士永恒豪华版毁灭战士4doom4 cdkey激活码PC中文steam正版
¥4.50
PC中文steam幽灵行者 国区CDKey激活码Ghostrunner Project Hel 赫尔计划 全DLC 冬季套装金牛礼包 霓虹套装
¥6.60
steam正版 毁灭战士永恒 PC游戏 国区激活码key DOOM Eternal 单人 线上对战 动作FPS射击游戏
¥348.00
PC中文正版steam 艾尔登法环 Elden Ring 老头环 国区cdkey激活码 正版游戏