我注意到的第一件事是你应该使用if
/else if
因为你真的只想抓住一个结构使它在视觉上更清晰相关的桶。
第二你是用出来做< >
排除一些数字或者是<=
或>=
,我的例子中,我选择了做min < variable <= max
,但你可以很容易地最小的变量。
为了清楚起见,我将其分离为函数并将其应用于数字原型以便于使用。
// check if given number is greater than min less than or equal to max
Number.prototype.between = function(min, max) {
return (this > min && this <= max);
}
// calculates your mileage amounts
const calcRate = distance => {
if (distance.between(0, 10)) {
return (distance * 50);
} else if (distance.between(10, 40)) {
return (((distance - 10) * 1.5) + (10 * 50));
} else if (distance.between(40, 100)) {
return (((distance - 40) * 2) + (10 * 1.5) + (10 * 50));
} else if (distance.between(100, 1000)) {
return (((distance - 100) * 2.5) + (40 * 2) + (10 * 1.5) + (10 * 50));
} else if (distance > 1000) {
// do something
}
}
// test variable
let miles = 120;
// test result
let result = calcRate(miles);
// log result
console.log(result);
它应该做什么? –
两个地理点的票价计算。 – bugHunter
您可能想要将价格放入其他变量中。将变量用于不同的目的是一个糟糕的主意。 –