我目前正在处理切换语句,并且在下面有一个小功能,将给定的数字分数转换为等级。或至少是它应该做的事情,但不知怎的,这一切都出错了,我不确定为什么!
function convertScoreToGrade(score) {
var grade = "";
switch(score) {
case 100>=score && score>=90: grade = "A";
break;
case 89>=score && score>=80: grade = "B";
break;
case 79>=score && score>=70: grade = "C";
break;
case 69>=score && score>=60: grade = "D";
break;
case 59>=score && score>=0: grade = "F";
break;
case score>100 || score<0: grade = "INVALID SCORE";
} return grade;
}
convertScoreToGrade(10);
例如,当我输入数字10时,我只得到一个空字符串,这表明相关案例没有被评估。任何帮助,将不胜感激。
答案 0 :(得分:0)
function convertScoreToGrade(score) {
// scores is an array of objects
// Each element in the scores array has two properties, grade and score
// grade is the letter grade, score is the minimum score to achieve that grade
var i,l,scores = [{ grade: 'A', score: 90},
{grade: 'B',score : 80},
{grade: 'C',score: 70},
{grade: 'D',score: 60 }];
// Ensure score is between 0 and 100 inclusive
if (score < 0 || score > 100) {
return 'Invalid';
}
// Loop through all the scores and exit when the score is larger than the minimum
l = scores.length;
for (i=0;i<l;i++) {
if (score >= scores[i].score) {
return scores[i].grade;
}
}
// If the score was not found, the grade is an F
return 'F';
}
console.log(convertScoreToGrade(82));
console.log(convertScoreToGrade(90));
console.log(convertScoreToGrade(50));
答案 1 :(得分:0)
您可能会想到的糟糕解决方案明显比替代方案更糟糕但我已经输入了它,我认为这有助于您理解这是您使用if语句处理它的方式。请怜悯我发布这样糟糕的代码。
function convertScoreToGrade(score) {
var grade = "";
if(score>=0){
grade = "F";
}
if(score>=60){
grade = "D";
}
if(score>=70){
grade = "C";
}
if(score>=80){
grade = "B";
}
if(score>=90){
grade = "A";
}
if (score>100 || score<0){
grade = "INVALID SCORE";
}
return grade;
}
convertScoreToGrade(10);
答案 2 :(得分:0)
根据您的示例,以下是修改以使您的代码正常工作
这里最重要的是你匹配传递给switch语句的参数。因此,传递布尔值为true意味着如果您的条件为真,那就是这种情况。
IMO,你应该在这种情况下使用switch语句。它只是少量案例(5),并且对于将在以后处理或维护此代码的任何人来说都是非常易读的。
function convertScoreToGrade(score) {
// Check for invalid scores first
if(typeof score !== 'number' || score < 0 || score > 100)
return "INVALID SCORE";
var grade = "";
// Pass a boolean value, remember we are matching this value
// EX: (score < 90) is true when score is 0 - 89
switch(true) {
case score < 60:
grade = "F";
break;
case score < 70:
grade = "D";
break;
case score < 80:
grade = "C";
break;
case score < 90:
grade = "B";
break;
case score <= 100:
grade = "A";
break;
}
// If you want partial grades
if(score % 10 <= 3 && score !== 100 )
grade += "-";
else if(score % 10 >= 7 || score == 100)
grade += "+";
return grade;
}
// These are small test cases to show you
// that convertScoreToGrade works as defined
console.log(convertScoreToGrade(-1));
console.log(convertScoreToGrade(101));
console.log(convertScoreToGrade('The dog ate it.'));
var i = 50;
while(i <= 100){
console.log(i, 'should be', convertScoreToGrade(i));
i += 4;
}
&#13;