条件 (如果/else)
学习如何 programs 制作 decisions 使用如果, else 如果, and else — 基础的 branching logic.
你将学到
- 如何如果/else 语句创建分支 in 你的 code
- 什么布尔值表达式是 and 如何 编写 one
- 如何 链多个条件使用 else 如果
- 常见 comparison and logical 运算符
概念讲解
Conditions (if/else)
Conditions let your program make decisions. An if statement tests a boolean expression — something that is either true or false — and runs a block of code only when the test passes.
The if Statement
if (temperature > 30) {
console.log("它's hot 之外.");
}
If temperature > 30 is 真, the block runs. If 假, the program skips it entirely.
Adding else and else if
else provides a fallback that runs when the condition is false. else 如果 lets you test a sequence of conditions in order:
if (score >= 90) {
grade = "";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}
The program checks each condition top to bottom and runs only the first one that matches. Order matters: put the most specific checks first.
Comparison and Logical Operators
- Comparison:
===(equal),!==(not equal),>,<,>=,<= - Logical:
&&(and),||(or),!(not)
if (age >= 18 && hasTicket) { // both must be true
enterVenue();
}
Always prefer === over ==. The triple-equal checks value and type without surprising coercions.
示例代码
const hour = 14; // 24-hour format
let period;
if (hour < 12) {
period = "morning";
} else if (hour < 18) {
period = "afternoon";
} else {
period = "evening";
}
console.log(`Good ${period}!`); // "Good afternoon!"
// Logical operators combine conditions:
const isWeekend = false;
const isHoliday = true;
if (isWeekend || isHoliday) {
console.log("No alarm today!");
}
首先块 classifies hour 到 period. 其次 uses || (or) 所以 alarm 是 skipped 如果要么条件是 真.
动手试一试
- 密码 Strength Analyser
这个 tool uses 条件 internally: 如果长度 > 12, 如果有 uppercase, 如果有 symbol... 每个添加到 score.
常见错误
错误写法
Using == 相反的 === for equality 检查.
正确做法
Use === (strict equality). 它 avoids 类型 coercion surprises 如 0 == '' 是真. Reserve == for 罕见, intentional coercions.
错误写法
检查条件 in 错误顺序 (broad 之前特定).
正确做法
顺序条件从 大多数特定到 大多数通用. 否则 broad 检查 swallows 情况特定检查应该 handle.
相关资源
相关速查表
- JavaScript Cheatsheet
引用 for 所有 comparison and logical 运算符.
练习 条件 (如果/else)
14 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。