Skip to content

if / else

JavaScript Lesson 7 2:21 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
An if in JavaScript has a shape you copy exactly. JavaScript 里的 if 有一个照抄就行的形状。
The word if, then round brackets holding the test — the boolean you learned to write last lesson. 先是 if,然后是圆括号,里面放判断——就是上一课你学会写的那个布尔值。
Then curly braces holding what to do when the test is true. 接着是花括号,里面放条件为真时要做的事。
Then, optionally, else with its own braces, which takes everything left over. 再往后,可以选择加上 else 和它自己的花括号,它接住剩下的所有情况。
The braces are what group the lines, so indentation here is for humans; the braces are for the machine. 是花括号把这些行归为一组,所以这里的缩进是给人看的;花括号才是给机器看的。
Here is what that shape means. 这个形状的含义是这样的。
The test is asked once. 判断只问一次。
If it is true, the first block runs and the else block is skipped entirely. 如果为真,第一个代码块执行,else 块被完全跳过。
If it is false, the else block runs and the first is skipped. 如果为假,else 块执行,第一个被跳过。
Exactly one of the two happens — never both, never neither. 两者中正好发生一个——不会两个都发生,也不会一个都不发生。
That is the whole idea, and every branching program you write is this picture, sometimes nested inside itself. 整个想法就是这样,而你写的每一个带分支的程序,都是这张图,有时是它自己套着自己。
With three outcomes you chain them with else if. 如果有三种结果,就用 else if 把它们串起来。
JavaScript checks from the top and stops at the first one that is true. JavaScript 从上往下检查,在第一个为真的地方停下。
Follow a mark of sixty-five. 跟着 65 分走一遍。
The first test fails — sixty-five is not seventy or more. 第一个判断不成立——65 没有达到 70。
The second is true, so it logs B. 第二个为真,于是打印 B。
And the else is never reached at all. 而 else 根本没被走到。
Order matters: put the widest test first and everything under it becomes unreachable. 顺序很重要:如果把范围最宽的判断放在最前面,它下面的都永远轮不到。
Now the lesson's third task, and it joins the last two lessons together. 现在做课程里的第三道题,它把前两课连了起来。
You already know how to ask whether a number is even — the remainder, compared to zero with three equals signs. 你已经会问一个数是不是偶数——取余,再用三个等号和 0 比较。
That whole expression is a boolean, so it goes straight into the brackets of the if. 整个这个表达式就是一个布尔值,所以它可以直接放进 if 的圆括号里。
No extra comparison, no equals true. 不用再多做一次比较,也不用写“等于 true”。
Four is even, so the first block runs and the console shows even. 4 是偶数,所以第一个代码块执行,控制台显示 even。
Four things to take with you. 带走四点。
One: the test goes in round brackets. 第一:判断写在圆括号里。
Two: what to do goes in curly braces, and the braces are what group the lines. 第二:要做的事写在花括号里,而正是花括号把这些行归为一组。
Three: else if is checked in order and the first true one wins. 第三:else if 按顺序检查,第一个为真的胜出。
Four: use three equals inside the test. 第四:判断里面用三个等号。
Now do the three tasks; the middle one wants a chain of three outcomes. 现在去做那三道题;中间那题要写出三种结果的链。

Log in or create account

IGCSE, A-Level & AP