Switch语句保持记录默认值


var income = parseInt(prompt('Please enter your income 
here.'))


switch (income){
case (income < 9701):
console.log ('Your tax rate is 10%');
break;
case (income > 9700 && income <= 39475):
console.log('Your tax rate is 12%');
break;
case (income > 39475 && income <= 84200):
console.log('Your tax rate is 22%');
break;
case (income > 84200 && income <= 160725):
console.log('Your tax rate is 24%');
break;
case (income > 160725 && income <= 204100):
console.log('Your tax rate is 32%');
break;
case (income > 204100 && income <= 510300):
console.log('Your tax rate is 35%');
break;
case (income >= 510300):
console.log('Your tax rate is 37%');
break;
default:
console.log('Please enter a valid income')
}

为什么这段代码一直将"默认"值记录到控制台?如果我在案例中加上等号,即案例(收入=9700(并输入9700,则它会记录("您的税率为10%"(。当我使用大于/小于或等于运算符时,代码将变为默认值。

就像大多数人在评论中所说的那样,不能那样使用switch语句。请在此处查看更具描述性的答案:大于/小于的切换语句

如果您想将您的解决方案切换到If/ELSE逻辑解决方案,这里有一个如何使用oneliners(三元运算符(格式化代码的示例:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

var income = parseInt(prompt('Please enter your income here.'))
var currentTaxBracket 
= income < 9701 ? 'Your tax rate is 10%' 
: income > 9700 && income <= 39475 ? 'Your tax rate is 12%'
: income > 39475 && income <= 84200 ? 'Your tax rate is 22%'
: income > 84200 && income <= 160725 ? 'Your tax rate is 24%'
: income > 160725 && income <= 204100 ? 'Your tax rate is 32%'
: income > 160725 && income <= 204100 ? 'Your tax rate is 35%'
: income >= 510300 ? 'Your tax rate is 37%'
: 'Please enter a valid income'
alert(currentTaxBracket)

您可以采用早期退出方法的函数,从最小值到最大值进行检查,并省略不必要的检查。

function getTaxRate(income) {
if (income < 9701) return 10;
if (income <= 39475) return 12;
if (income <= 84200) return 22;
if (income <= 160725) return 24;
if (income <= 204100) return 32;
if (income <= 510300) return 35;
return 37;
}
var income = parseInt(prompt('Please enter your income here.')),
rate = income > 0 && getTaxRate(income);
console.log(rate
? `Your tax rate is ${rate}%`
: 'Please enter a valid income'
);

最新更新