0
function getRankForScore(score){
         if(score <= 20)        return 1;
    else if(21 < score <=40)    return 2;
    else if(41 < score <=60)    return 3;
    else if(61 < score <=90)    return 4;
    else return 5;
}

getRankForScore(10)// 返回1,预期

getRankForScore(22)//返回2,预期

getRankForScore(50 or any number > 21)// 返回2.

我如何使用 switch case 构造来进行不等式检查?上述功能有什么问题?

4

9 回答 9

7

Because

when when you enter number greater than 21 the condition 21 < score evaluates to true and returns 1 which is then compared with 40, which is obviously less than 40

于 2013-09-09T07:56:04.910 回答
4

Your syntax was wrong in the else if's:

function getRankForScore(score){
    if(score <= 20)         return 1;
    else if(score <= 40)    return 2;
    else if(score <= 60)    return 3;
    else if(score <= 90)    return 4;
    else return 5;
}
于 2013-09-09T07:56:17.400 回答
3

您可以在此处使用 oneliner,使用短路评估

function getRankForScore(score){
 return score <= 20 && 1 || score <=40 && 2 || 
        score <= 60 && 3 || score <=90 && 4 || 5;
}
于 2013-09-09T08:03:35.097 回答
2

a < b < c is not what you expect, it is interpreted as (a < b) < c which becomes (for example) true < c.

于 2013-09-09T07:57:28.967 回答
1
function getRankForScore(score) {
    var result;

    switch(true) {
       case score <= 20:
           result = 1;
           break;
       case score > 21 && score <= 40:
           result = 2;
           break;
       case score > 41 && score <= 60:
           result = 3;
           break;
       case score > 61 && score <= 90:
           result = 4;
           break;
      default:
           result = 5;
    }

    return result;
}
于 2013-09-09T08:01:09.207 回答
0

Why don't you use a code like:

function getRankForScore(score) {
    if(score <= 20) {
        return 1;
    } else if(score > 21 && score <= 40) {
        return 2;
    } else if(score > 41 && score <= 60) {
        return 3;
    } else if(score > 61 && score <= 90) {
        return 4;
    } else {
        return 5;
    }
}
于 2013-09-09T07:57:17.620 回答
0

Try this way:

function getRankForScore(score){
         if(score <= 20)        return 1;
    else if(score >21 && score <=40)    return 2;
    else if(score > 41 && score <=60)    return 3;
    else if(score> 61 && score <=90)    return 4;
    else return 5;
}

The expression if (a < b < c) is not leagal.

于 2013-09-09T07:57:47.760 回答
0

这就是为什么:

function getRankForScore(score){
         if(score <= 20)        return 1;
    else if(score > 21 && score <= 40)    return 2;
    else if(score > 41 && score <= 60)    return 3;
    else if(score > 62 && score <= 80)    return 4;
    else return 5;
}

alert(getRankForScore(42));

Javascript 有时不是数学 :(

你不能做 21 < score <= 40,你必须使用 && 语句。

在这里工作小提琴:http: //jsfiddle.net/BaJse/

于 2013-09-09T07:58:09.420 回答
0

我认为当你写这样的东西时:

if(21 < score <=40)

它实际上等于:

if (21 < score || score <= 40)

适合你的情况。任何大于 21 的数字 - 这就是为什么它不会继续检查您的其他 if 语句。

你应该做一个 AND 声明:

if (21 < score && score <= 40)
于 2013-09-09T07:59:21.830 回答