首页 > 解决方案 > 字符串问题:如何使用 javascript 进行评分

问题描述

我无法实现将参数rating作为字符串并返回值的函数tipPercentage :

  1. 糟糕或糟糕,然后返回 3
  2. 好或好,然后返回 10
  3. 优秀,回报 20
  4. 以上都不是,返回0

自定义测试的输入格式必须是第一行包含一个整数n,表示rating的值

帮助初学者!!!

标签: javascriptstringfunctionpercentagerating

解决方案


您可以使用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))
}


推荐阅读