条件分支(conditional branch)让程序可以根据不同情况执行不同代码。JavaScript 使用 if、else if、else 来描述这些分支。
if
if 会判断一个条件。如果条件为 true,就执行花括号中的语句块(block);如果条件为 false,就跳过这个语句块。
let age = 17;
if (age > 0 && age < 18) {
console.log("Minor");
}一次可能的运行结果:
请输入年龄:17
未成年人花括号决定哪些语句属于 if。缩进(indentation)不是强制语法,但保持一致缩进能让语句块更清楚,也能减少错误。
知识测验
题目
在 JavaScript 中,什么符号决定哪些语句属于 if 代码块?
if-else
if-else 用于二选一:条件为 true 时执行 if 语句块,否则执行 else 语句块。
下面用闰年(leap year)判断作为例子。一个年份是闰年,需要满足以下条件之一:
- 能被 4 整除,并且不能被 100 整除。
- 或者能被 400 整除。
let year = 2020;
let leap = (year % 4 === 0 && year % 100 !== 0)
|| year % 400 === 0;
if (leap) {
console.log("Leap year");
} else {
console.log("Common year");
}一次可能的运行结果:
请输入年份:2020
闰年这里把复杂条件先保存到 is_leap_year,可以让 if 那一行更清晰。写真实程序时,这种方式通常比把一长串判断直接塞进 if 更好维护。
知识测验
题目
在 if-else 中,当 if 条件为 false 时会发生什么?
if-else if-else
当情况不止两种时,可以使用多分支结构if-else if-else。程序会从上到下检查条件,遇到第一个为 true 的分支就执行,并跳过后面的分支。
let c = 'T';
if (c >= 'a' && c <= 'z') {
console.log("Lowercase");
} else if (c >= 'A' && c <= 'Z') {
console.log("Uppercase");
} else if (c >= '0' && c <= '9') {
console.log("Digit");
} else {
console.log("Special character");
}一次可能的运行结果:
请输入一个字符:T
大写字母else if 的顺序很重要。你应该把更具体、更优先的条件放在前面,把兜底情况放在 else 中。
互动实验
分支路径追踪器
访问权限免费
点击一个字符,看 JavaScript 从上到下检查条件,并停在第一个 true 分支。
'a' ≤ c ≤ 'z'
'A' ≤ c ≤ 'Z'
'0' ≤ c ≤ '9'
else
知识测验
题目
if-else if-else 中,如果第一个为 true 的分支已经执行,后面的 else if 会怎样?
动手练习
实现一个分段函数
按照不同区间给 x 赋予不同公式,最后输出 y。
- 当 x < -2 时,令 y = 0.5 * x + 3。
- 当 -2 <= x <= 2 时,令 y = 0。
- 否则令 y = Math.pow(4, x),并输出结果。