if / else
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Making decisions
if (test) { ... }runs its block only when the test istrue.elsegives the path to take when the test isfalse.
中文
做决定
if (test) { ... }只有在测试为true时才运行它的代码块。else给出测试为false时要走的路。
let age = 20;
if (age >= 18) {
console.log("adult"); // → adult
} else {
console.log("minor");
}
English
Many paths with else if
- Add
else iffor more choices. JavaScript checks each test top to bottom. - The first test that is
truewins; the rest are skipped.
中文
用 else if 走多条路
- 加上
else if提供更多选择。JavaScript 从上到下检查每个测试。 - 第一个为
true的测试胜出;其余的都被跳过。
let mark = 72;
if (mark >= 70) {
console.log("A"); // → A
} else if (mark >= 50) {
console.log("B");
} else {
console.log("C");
}
Explore · 探索
Which branch runs? · 哪个分支会运行?
Tests are checked top-down; the first · 第一个 true one runs and the rest are skipped. · 测试从上往下检查;第一个为真的运行,其余跳过。
English
Watch out
- Put the test in
( )and the block in{ }. - Inside a test, compare with
===(day === "Sat"), never a single=.
中文
注意
- 测试放在
( )里,代码块放在{ }里。 - 在测试里用
===比较(day === "Sat"),绝不要只写一个=。
English
Common mistakes
- The condition goes in
( )and the body in{ }. - Compare with
===.
中文
常见错误
- 条件写在
( )里,主体写在{ }里。 - 比较用
===。
English
Now you try
- Read the value, then choose with
if/else. - Press Check answer to test it.
中文
现在轮到你
- 读取值,然后用
if/else选择。 - 按检查答案来测试它。
let n = 5. If n is greater than 0 log positive, otherwise log not positive. (It should log positive.) · let n = 5。如果 n 大于 0 就打印 positive,否则打印 not positive。(应打印 positive。)
Click Run to see the output here. · 点击“运行”查看此处输出。
let mark = 65. Log A for 70 or more, B for 50–69, and C for less. (It should log B.) · let mark = 65。70 及以上打印 A,50–69 打印 B,更低打印 C。(应打印 B。)
Click Run to see the output here. · 点击“运行”查看此处输出。
let n = 4. Log even if n % 2 === 0, otherwise log odd. (It should log even.) · let n = 4。如果 n % 2 === 0 就打印 even,否则打印 odd。(应打印 even。)
Click Run to see the output here. · 点击“运行”查看此处输出。