在 JavaScript 中,可以使用下面的关系运算符和相等运算符来比较数字。
| 比较 | 运算符 |
|---|---|
| 大于 | a > b |
| 大于或等于 | a >= b |
| 小于 | a < b |
| 小于或等于 | a <= b |
| 严格相等 | a === b |
| 非严格相等 | a !== b |
比较的结果始终是一个布尔值:true或false。
1 < 3;
// => true
2 !== 2;
// => false
1 === 1.0;
// => true
// All numbers are floating-points, so this is different syntax for
// the exact same value.
在 JavaScript 中,上面的比较运算符也可以用来比较字符串。这时会按照字典顺序进行比较。你可以在这里找到所有字符确切顺序的列表。
'Apple' > 'Pear';
// => false
'a' < 'above';
// => true
'a' === 'A';
// => false
在 JavaScript 中,有条件地执行逻辑的常见方式是if语句。它由if关键字、用圆括号括起来的条件,以及用大括号括起来的代码块组成。只有当条件的求值结果为true时,才会执行这个代码块。
if (condition) {
// code that is executed if "condition" is true
}
它既可以单独使用,也可以和else关键字结合使用。
if (condition) {
// code that is executed if "condition" is true
} else {
// code that is executed otherwise
}
要在else语句中嵌套另一个条件,可以使用else if。
if (condition1) {
// code that is executed if "condition1" is true
} else if (condition2) {
// code that is executed if "condition2" is true
// but "condition1" was false
} else {
// code that is executed otherwise
}
在这个练习中,你将编写一些代码,帮助你为购买一辆车做好准备。
你需要完成三项任务:一项是判断你是否需要驾照,一项是帮你在两辆车之间做选择,还有一项是估算一辆二手车的合理价格。
有些类型的车辆需要驾照才能驾驶。
假设只有 'car' 和 'truck' 这两种类型需要驾照,其他所有类型都可以在没有驾照的情况下驾驶。
实现 needsLicense(kind) 函数,它接受车辆的类型,并返回一个布尔值,表示这种车辆是否需要驾照。
needsLicense('car');
// => true
needsLicense('bike');
// => false
你评估了当前可选的车辆。
你把范围缩小到了两个选项,但需要有人帮你做最终决定。
为此,请实现 chooseVehicle(option1, option2) 函数,它接受两辆车作为实参,并返回一个决定,其中包含按字典顺序排在前面的那个选项。
chooseVehicle('Wuling Hongguang', 'Toyota Corolla');
// => 'Toyota Corolla is clearly the better choice.'
chooseVehicle('Volkswagen Beetle', 'Volkswagen Golf');
// => 'Volkswagen Beetle is clearly the better choice.'
既然你已经做出了决定,你想确保在经销商那里能以公道的价格买到车。 由于你打算买一辆二手车,价格就取决于这辆车的车龄。 做个粗略估算:如果车龄不到 3 年,价格就是它全新时原价的 80%。 如果车龄超过 10 年,价格就是原价的 50%。 如果车龄至少 3 年但不超过 10 年,价格就是原价的 70%。
实现 calculateResellPrice(originalPrice, age) 函数,用 if、else if 和 else 来应用这套逻辑(如果你想多加练习,也可以用别的方式)。
它接受原价和车龄作为实参,并返回该车在经销商处的估算价格。
calculateResellPrice(1000, 1);
// => 800
calculateResellPrice(1000, 5);
// => 700
calculateResellPrice(1000, 15);
// => 500