学习如何计算、如何用 === 比较值,并让你的程序用 if 和 else 做出决策。
在 Kodokon 中打开本课运算符是对值执行某种运算的符号。你在学校已经认识了算术运算符:+(加法)、-(减法)、*(乘法)和 /(除法)。JavaScript 还增加了 %,即取模运算符,它给出整数除法的余数:例如用来判断一个数是不是偶数就很方便。
const a = 10;
const b = 3;
console.log(a + b); // Prints: 13
console.log(a - b); // Prints: 7
console.log(a * b); // Prints: 30
console.log(a % b); // Prints: 1 (the remainder)为了做出决策,程序需要比较各个值。比较是一个答案为布尔值(true 或 false)的问题。比较运算符有:>(大于)、<(小于)、>=(大于或等于)、<=(小于或等于)、===(严格相等)和 !==(严格不等)。=== 运算符会检查两个值是否相同并且类型一致。
console.log(5 > 3); // true
console.log(5 < 3); // false
console.log(5 >= 5); // true
console.log(5 === 5); // true
console.log(5 === "5"); // false: different types
console.log(5 !== 3); // true该做决策了!if 语句只在条件为真时才运行一段代码。else 块则在条件为假时运行。条件写在圆括号之间,每个代码块写在花括号 { } 之间。
const age = 17;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
// Prints: You are a minor.5 === "5" 的值是什么?if / else 结构中,else 块什么时候运行?