问题描述
我无法实现将参数 rating 作为字符串并返回值的函数 tipPercentage :
- 糟糕或糟糕,然后返回3
- 好还是好,然后返回10
- 优秀,返回20
- 以上都不是,返回0
自定义测试的输入格式必须为第一行包含整数 n ,表示 rating
的值请帮忙!
解决方法
您可以使用switch statement相对容易地做到这一点,我们会检查输入等级,然后返回相关的小费百分比。
如果我们没有给小费的百分比,我们将退回到默认条件,并返回0。
尽管switch语句可能更灵活,但是也可以使用地图。
// Takes rating as a string and return the tip percentage as an integer.
function tipPercentage(rating) {
switch ((rating + "").toLowerCase()) {
case "terrible":
case "poor":
return 3;
case "good":
case "great":
return 10;
case "excellent":
return 20;
default:
return 0;
}
}
let ratings = ["excellent","good","great","poor","terrible","meh",null];
for(let rating of ratings) {
console.log(`tipPercentage(${rating}):`,tipPercentage(rating))
}
,
<add key="ida:RedirectUri" value="https://localhost/AppTest/" />
,
您可以只使用一个对象来代替switch语句:
const tipPercentage = {
'excellent': 20,'good': 10,'great': 10,'terrible': 3,'poor': 3,}
const myRatings = [
"excellent","whatever",undefined
];
for (let rating of myRatings) {
// Tip percentage,or 0 if it doesn't exist
console.log(rating,tipPercentage[rating] || 0)
}