包含小于等于或大于等于的Switch语句

问题描述 投票:0回答:0

我正在尝试 CodeWars 简单挑战来计算 BMI 并返回体重不足 - 肥胖的体重评级。我对如何在 switch 语句中实现这一点特别感兴趣,因为我已经提交了 If + If else 变体。 此外,就清洁代码/性能而言,switch 语句何时变得更加可行。

最初我提交了 if else 变体。

function bmi(weight, height) {
 let bmiCalc = (weight / (height*height));

if (bmiCalc <= 18.5){
 return 'Underweight';
if else (bmiCalc <= 25.0){
 return 'Normal';
if else (bmiCalc <= 30.0){
 return 'Normal';
else (bmiCalc > 30.0){
 return 'Obese';
 }
}

然后我想知道 switch 语句会是什么样子,所以我尝试了

function bmi(weight, height) {
  let bmiCalc = (weight / (height * height));
  
  switch (bmiCalc){
      case (<= 18.5):
        return 'Underweight';
      case (<= 25.0):
        return 'Normal';
      case (<= 30.0):
        return 'Overweight';
      case (> 30.0):
        return 'Obese';
  }
}

最终吐出一个意想不到的token'<=' error. Is it possible to have such expressions in a switch statement.

我也试过放入

case (bmiCalc <= 18.5){ return 'Underweight'}

根据我在其他语言中的发现,我发现这个表达式不适用于我想要的测试用例。提前致谢,希望问题不会太愚蠢。

javascript if-statement switch-statement expression
© www.soinside.com 2019 - 2024. All rights reserved.