JavaScript,我无法理解开关参数



我最近开始学习javascript我目前正在乌代米观看Javascript课程。虽然代码具有挑战性,但关于"切换"的参数,我无法理解

let john = {
fullName: 'John Smith',
bills: [124, 48, 268, 180, 42],
calcTips: function() {
this.tips = [];
this.finalValues = [];
for (let i = 0; i < this.bills.length; i++) {
let percentage;
let bill = this.bills[i]
switch (bill) { // If I put parameter as 'bill' variation, The result is only defalut.
case bill < 50:
percentage = 0.2;
break;
case bill >= 50 && bill < 200:
percentage = 0.15;
break;
default:
percentage = 0.1;
}

this.tips[i] = bill * percentage;
this.finalValues[i] = bill + bill * percentage;
}
}
}
john.calcTips();
console.log(john);

然而

let john = {
fullName: 'John Smith',
bills: [124, 48, 268, 180, 42],
calcTips: function() {
this.tips = [];
this.finalValues = [];
for (let i = 0; i < this.bills.length; i++) {
let percentage;
let bill = this.bills[i]
switch (true) { // If I put 'ture' as a parameter, It work's. Why?
case bill < 50:
percentage = 0.2;
break;
case bill >= 50 && bill < 200:
percentage = 0.15;
break;
default:
percentage = 0.1;
}
this.tips[i] = bill * percentage;
this.finalValues[i] = bill + bill * percentage;
}
}
}
john.calcTips();
console.log(john);

我在谷歌上搜索过这个问题。但我找不到具体的方法来解决这个问题。我会感谢你的帮助。

Switch语句严格比较值。这意味着您可以比较开关变量的确切值。

switch (x) {
case 1: console.log(1); break;
case 2: console.log(2); break;
}

然而,如果你想让switch语句在这样的数字范围内工作,你可以做一个技巧:

var x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x < 9):
alert("between 5 and 8");
break;
case (x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}

实现基于布尔值的严格比较。switch语句适用于true,并且只要情况为true,它就会匹配。

相关问题:打开JavaScript 中的整数范围

switch语句测试变量的值,并将其与多个情况进行比较。一旦找到案例匹配,就会执行与该特定案例相关联的语句块。所以在这种情况下,你打开一个常数值。

更多详细信息:javascript:在切换情况中使用条件

最新更新