导航
×
   ❮   
HTML CSS JavaScript PHP Go ECMS

JavaScript 教程

JS 简介 JS 如何使用 JS 输出 JS 语法 JS 语句 JS 注释 JS 变量 JS 运算符 JS 条件语句 JS 循环 JS 字符串 JS 数字 JS 函数 JS 对象 JS 日期 JS 数组 JS 类型化数组 JS 集合 JS Map 映射 JS Math JS 正则表达式 JS 数据类型 JS 错误 JS 事件 JS 编程 JS 关键字参考 JS 保留关键字参考 JS 运算符参考 JS 运算符优先级 JS UTF-8 字符 JS UTF-8 符号 JS UTF-8 表情符号 JS 版本

JavaScript if else 语句


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


条件语句

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

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

在 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% 的机会。


freew3c.com 中文网是独立运营的中文开发者学习平台,与 freew3c.com 无关联。提供的内容仅用于学习和测试,不保证内容的正确性。


Copyright @2020-2026 京ICP备888888号-8