字符串问题:如何使用JavaScript进行评级

问题描述

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

  1. 糟糕或糟糕,然后返回3
  2. 好还是好,然后返回10
  3. 优秀,返回20
  4. 以上都不是,返回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)
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...