Why does my switch statement parameter require a boolean?

时间:2017-11-14 23:51:21

标签: javascript function switch-statement boolean

From my understanding, inside a switch statement parameter is supposed to be the item you are comparing against all your cases and returns the correct case.

My question is why does my switch statement require I put in the boolean true and not the "score" argument to which I am comparing all my cases? Thanks!

Heres the exercise

function convertScoreToGrade(score) {
  switch (true) {
    case (score > 100 || score < 0):
      return 'INVALID SCORE';
      break;
    case (score <=100 && score >= 90):
      return 'A';
      break;
    case (score <=89 && score >= 80):
      return 'B';
      break;
    case (score <=79 && score >= 70):
      return 'C';
      break;
    case (score <=69 && score >= 60):
      return 'D';
      break;
    case (score <=59 && score >= 0):
      return 'F';
      break;
  }
  return score;
}

1 个答案:

答案 0 :(得分:1)

因为JS在与switch参数进行比较之前在括号中计算表达式。考虑这个例子:

convertScoreToGrade(71);

function convertScoreToGrade(score) {
  switch (true) {
    case (false):
      return 'INVALID SCORE';
      break;
    case (false):
      return 'A';
      break;
    case (false):
      return 'B';
      break;
    case (true):
      return 'C';
      break;
    case (false):
      return 'D';
      break;
    case (false):
      return 'F';
      break;
  }
  return score;
}

很好的解释in this answer