javascript - 字符串问题:如何使用 javascript 进行评分
问题描述
我无法实现将参数rating作为字符串并返回值的函数tipPercentage :
- 糟糕或糟糕,然后返回 3
- 好或好,然后返回 10
- 优秀,回报 20
- 以上都不是,返回0
自定义测试的输入格式必须是第一行包含一个整数n,表示rating的值
帮助初学者!!!
解决方案
您可以使用switch 语句相对容易地做到这一点,我们检查输入评分,然后返回相关的小费百分比。
如果我们没有评分的小费百分比,我们将回退到默认条件,并返回 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))
}
推荐阅读
- ios - 在 UItableview 单元中重用计时器
- excel - 替换特定位置的单元格值
- python - TypeError:“FormData”对象不可迭代
- monaco-editor - 使用 monaco-editor 编辑本地文件
- python - 如何打乱数据框中的元素
- java - 如何将数据从回收器视图按钮传递到片段?[科特林或 java]
- visual-studio-code - VSCode 终端 - 更改当前工作目录的颜色
- docker - 具有大型共享代码库的多个云运行服务
- kubernetes - 为什么在为 rego 策略应用 constraint.yaml 时显示错误?
- raspberry-pi - Vnc 没有连接到树莓派