如何在JavaScript中将IF转换为SWITCH语句?

问题描述 投票:4回答:1

我已经完成了一项任务,我已经解决了很多问题,但需要进行一些小的修正,我需要某人帮助指出我在哪里对我的代码进行一些修改:

这是任务:

将多条件if语句示例代码转换为switch示例代码。

var myAge = parseInt(prompt("Enter your age", 30), 10);

if (myAge >= 0 && myAge <= 10) {
  document.write("myAge is between 0 and 10<br />");
}

if (!(myAge >= 0 && myAge <= 10)) {
  document.write("myAge is NOT between 0 and 10<br />");
}

if (myAge >= 80 || myAge <= 10) {
  document.write("myAge is 80 or above OR 10 or below<br />");
}

if ((myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89)) {
  document.write("myAge is between 30 and 39 or myAge is " + "between 80 and 89");

}
<DOCTYPE html>

  <html lang="en">
  <head>
    <title>SOME CODE</title>
  </head>

  <body>
  </body>
  </html>

因此,30岁以下的违约结果是:

myAge不在0到10之间,myAge介于30到39之间,或myAge是

在80到89之间

这是我到目前为止所做的:

var myAge = parseInt(prompt("Enter your age", 30), 10); // Get the user's response, converted to a number
switch (true) { // Switch statement if the condition is True
  case myAge >= 0 && myAge <= 10: // Check the inputs value in range 0 - 10                     
    document.write("myAge is between 0 and 10<br/>");
    break;
  case (!(myAge >= 0 && myAge <= 10)): // Check the inputs value if it's not a in range between 0 - 10 ( !(myAge >= 0 && myAge <= 10) )
    document.write("myAge is NOT between 0 and 10<br/>");
    break;
  case myAge >= 80 || myAge <= 10: // Check the inputs value if it's greater/equal to 80 OR less/equal to 10
    document.write("myAge is 80 or above OR 10 or below<br/>");
    break;
  default:
    document.write("myAge is between 30 and 39 or myAge is " + "between 80 and 89"); // Check the inputs value in range 30 - 39 And 80 - 89 

}
<DOCTYPE html>

  <html lang="en">
  <head>
    <title>Chapter 3, Example 2</title>
  </head>
  <body>
  </body>
  </html>

而且,正如您所看到的,结果略有不同。我打印了这个:

myAge不在0到10之间

我知道解决方案很简单,但不幸的是我无法解决它,因此它会打印出一个:

myAge不在0到10之间,myAge介于30到39之间,或myAge是

同样。

拜托,有人,帮我解决一下,我真的很感激!

javascript if-statement switch-statement
1个回答
1
投票

嵌套开关案例

var myAge = parseInt(prompt("Enter your age", 30), 10);

switch (true) {
  case myAge >= 0 && myAge <= 10:
    document.write("myAge is between 0 and 10<br/>");
  default:
    switch (true) {
      case (!(myAge >= 0 && myAge <= 10)):
        document.write("myAge is NOT between 0 and 10<br/>");
      default:
        switch (true) {
          case myAge >= 80 || myAge <= 10:
            document.write("myAge is 80 or above OR 10 or below<br/>");
          default:
            switch (true) {
              case (myAge >= 30 || myAge <= 39) || (myAge >= 80 && myAge <= 89):
                document.write("myAge is between 30 and 39 or myAge is " + "between 80 and 89");
            }
        }
    }
}

原因:

  1. 由于你使用了if系列,而不是if-else-if,这意味着我们不应该在Switch中使用break语句
  2. 如果我们不使用break,控件就会掉线,所以不检查连续的case的条件
  3. 强制条件检查的唯一方法是在default关键字后使用嵌套的Switch语句!
© www.soinside.com 2019 - 2024. All rights reserved.