JS 条件语句

创建于 2024-12-03 / 25
字体: [默认] [大] [更大]

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


条件语句

在您写代码时,经常会需要基于不同判断执行不同的动作。

您可以在代码中使用条件语句来实现这一点。

在 JavaScript 中,我们可使用如下条件语句:

  • 使用 if 来规定要执行的代码块,如果指定条件为 true
  • 使用 else 来规定要执行的代码块,如果相同的条件为 false
  • 使用 else if 来规定要测试的新条件,如果第一个条件为 false
  • 使用 switch 来规定多个被执行的备选代码块

switch 语句将在下一章中介绍。


if 语句

请使用 if 语句来规定假如条件为 true 时被执行的 JavaScript 代码块。

语法

if (condition) {
  //  条件为 true 时执行的代码块
}

注释:if 使用小写字母。大写字母(IF 或 If)会产生 JavaScript 错误。

实例

Make a "Good day" greeting if the hour is less than 18:00:

if (hour < 18) {
  greeting = "Good day";
}

The result of greeting will be:

亲自试一试 »

else 语句

请使用 else 语句来规定假如条件为 false 时的代码块。

if (condition) {
  //  条件为 true 时执行的代码块
} else {
  //  block of code to be executed if the condition is false
}

实例

如果 hour 小于 18,创建 "Good day" 问候,否则 "Good evening":

if (hour < 18) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}

greeting 的结果:

亲自试一试 »

else if 语句

请使用 else if 来规定当首个条件为 false 时的新条件。

语法

if (condition1) {
  //  block of code to be executed if condition1 is true
} else if (condition2) {
  //  block of code to be executed if the condition1 is false and condition2 is true
} else {
  //  block of code to be executed if the condition1 is false and condition2 is false
}

实例

如果时间早于 10:00,则创建 "Good morning" 问候,如果不是,但时间早于 18:00,则创建 "Good day" 问候,否则创建 "Good evening":

if (time < 10) {
  greeting = "Good morning";
} else if (time < 20) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}

greeting 的结果:

亲自试一试 »

更多实例

随机链接
本实例会把链接写入 W3School 或世界动物基金会(WWF)。通过使用随机数,每个链接都有 50% 的机会。


学习训练

练习题:

修正if语句,在x大于y时提醒 "Hello World"。

if x > y 
  alert("Hello World");


开始练习



0 人点赞过