为什么这个简单的switch语句总是运行默认值

Coo*_*ker 0 javascript switch-statement conditional-statements

好的,大家好!这个switch语句永远注定是行不通的。

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

然后,在第一种情况下,如果x小于0.5,则它将只是console.log“ less”。如果x大于0.5,它将只是console.log“ more”。如果由于某种原因程序无法按预期运行,则默认值为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);
Run Code Online (Sandbox Code Playgroud)

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

Cer*_*nce 5

switch将您switchcases 进行比较。因此,如果您有case x < 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);
Run Code Online (Sandbox Code Playgroud)

如果你switchx自己,一个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);
Run Code Online (Sandbox Code Playgroud)

但这根本不够灵活,也不是您想要的。

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

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');
}
Run Code Online (Sandbox Code Playgroud)