【问题标题】:why does this simple switch statement always run the default为什么这个简单的switch语句总是运行默认
【发布时间】:2019-10-30 01:12:35
【问题描述】:

好吧,看来这个 switch 语句注定永远行不通。

最初的想法是创建一个变量 x,它是一个提示,用户必须选择输入任何数字,这将是 x 的值。

那么在switch的第一种情况下,如果x小于0.5那么就会简单的console.log“less”。 如果 x 大于 0.5,它将简单地 console.log “更多”。 如果由于某种原因程序没有按预期工作,默认是 console.log “这是默认值”

然后我最后添加了一个 x 的 console.log,只是为了知道用户输入了什么数字。

让我们试试吧!

我试了又试,无论我输入什么数字,它总是打印“这是默认值”。然后打印 x 的值。

我最终选择了 Rambo 并删除了提示并将 x 声明为 0.6。它应该打印“更多”,但它仍然没有。

var x = 0.6;

switch (x) {
  case x < 0.5:
    console.log("less");
    break;
  case x > 0.5:
    console.log("more");
    break;

  default:
    console.log("its the dflt");
};

console.log(x);

所以我想知道这段代码有什么问题。帮助

【问题讨论】:

  • 感谢某些性能,我确定有人在迷惑我的代码哈哈

标签: javascript switch-statement conditional-statements


【解决方案1】:

switch 将您的 switchcases 进行比较。因此,如果您有要运行的 case x &lt; 0.5:,那么如果您 switched 反对的表达式是 true,则该案例将运行:

var x = 0.6;

switch (true) {
  case x < 0.5:
    console.log("less");
    break;
  case x > 0.5:
    console.log("more");
    break;

  default:
    console.log("its the dflt");
};

console.log(x);

如果您将switchx 本身相对,则case 将仅在case 评估为与x 相同的值时运行,此处为0.6,例如:

var x = 0.6;

switch (x) {
  case 0.6:
    console.log('x is exactly 0.6');
    break;
  default:
    console.log("x is something other than 0.6");
};

console.log(x);

但这一点都不灵活,也不是你想要的。

就个人而言,我更喜欢if/else,它更容易阅读(而且,正如一些在 cmets 中指出的那样,速度要快得多):

var x = 0.6;
if (x < 0.5) {
    console.log("less");
} else if (x > 0.5) {
    console.log("more");
} else {
    console.log('neither less nor more; equal or NaN');
}

【讨论】:

  • 或者switch (x&gt;5)case true/falsedefault,尽管在OP的用例中使用switch是相当多余的。
  • 请不要使用switch(true)stackoverflow.com/a/12259830/36866
【解决方案2】:

CertainPerformance 已经很好地回答了您的问题,但是如果您仍然不了解如何使用 switch,我建议您使用“if 语句”,直到您有时间阅读有关使用 switch 的更多信息。

var x = 0.6;

if (x < 0.5) {
  console.log("less");
}
else if (x > 0.5) {
  console.log("more");
}
else {
  console.log("its the dflt");
}

console.log(x);

希望这对你来说更容易:)

【讨论】:

    【解决方案3】:

    Switch 将x 的值与案例的 进行比较。在您的代码中,x &lt; 0.5 的计算结果为 true。 switch case 不是像 if 语句那样去那种情况,而是比较 xtrue。由于x 是一个数字,x 永远不会等于true,因此始终采用默认情况。

    在这种情况下,我会使用 if 语句而不是 switch。开关更适合枚举(检查 x 是否是一组值中的一个特定值,而不是一个值范围)

    【讨论】:

      猜你喜欢
      • 2014-08-08
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      相关资源
      最近更新 更多