Skip to content

Booleans and comparisons

JavaScript Lesson 6 2:28 English narration · English + 中文 subtitles burned in

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

Chapters

Transcript
So far your values have been numbers and strings. 到目前为止,你用的值不是数字就是字符串。
Here is a third kind, and it has only two values in the whole world: true and false. 这里是第三种,而它在整个世界里只有两个值:true 和 false。
It is called a boolean, after George Boole, and it is what every comparison hands back. 它叫布尔值,名字来自 George Boole,而每一个比较返回的都是它。
Ten is the same as ten, so that gives true. 10 和 10 相同,所以得到 true。
Eight is greater than three, true again. 8 大于 3,又是 true。
Three is the same as four — false. 3 和 4 相同吗——false。
No maybes. 没有“可能”。
Now the part of this lesson that matters most. 现在讲这一课最重要的部分。
JavaScript has two ways to ask whether things are the same. JavaScript 有两种方式问“是不是一样”。
With two equals signs, it converts one side before comparing — so the text five equals the number five is true, which is almost never what you meant. 用两个等号,它会先把一边转换再比较—— 于是文字 "5" 等于数字 5 是 true,而这几乎不会是你的本意。
With three equals signs there is no conversion: different kinds are simply not equal, so you get false. 用三个等号就不做转换:种类不同就是不相等,所以得到 false。
Three compares the value and the kind, and that is the one to use, every time. 三个等号同时比较值和种类,而这就是你每次都该用的那一个。
One question is often not enough. 一个问题常常不够用。
Double ampersand means and: both sides must be true. 双与号表示“并且”:两边都必须为真。
Double pipe means or: at least one side is true. 双竖线表示“或者”:至少有一边为真。
And an exclamation mark means not — it flips it. 感叹号表示“非”——它把结果反过来。
The teenager test in this lesson needs the first: thirteen or more, and nineteen or less, both at once. 这一课判断青少年要用第一个:13 岁及以上,并且 19 岁及以下,两个同时成立。
A value like twenty-five passes the first half and fails the whole thing. 像 25 这样的值通过了前半个条件,整体却是假。
Now the lesson's third task: is a number even? 现在做课程里的第三道题:这个数是不是偶数?
The test is one line and it happens in two steps. 判断只有一行,但分两步发生。
The remainder first: eight percent two is zero. 先算余数:8 % 2 等于 0。
Then compare that to zero with three equals signs, and you get true. 再用三个等号把它和 0 比较,得到 true。
Percent binds tighter than the comparison, so no brackets are needed — though adding them never hurts if it reads more clearly to you. 百分号的优先级高于比较,所以不需要括号—— 不过如果加上括号你读起来更清楚,那也没有坏处。
Four things to take with you. 带走四点。
One: a boolean is true or false, and nothing else. 第一:布尔值只有 true 或 false,没有别的。
Two: three equals signs compares the value and the kind. 第二:三个等号同时比较值和种类。
Three: two equals signs converts first, which is why you should avoid it. 第三:两个等号会先转换,所以应该避免使用它。
Four: double ampersand needs both sides, double pipe needs one, and an exclamation mark flips it. 第四:双与号要求两边都成立,双竖线只要一边,感叹号把结果反过来。
Now do the four tasks; the last one combines two comparisons. 现在去做那四道题;最后一题要把两个比较合起来。

Log in or create account

IGCSE, A-Level & AP