简体   繁体   English

为什么“if”有效,而“switch”无效?

[英]Why “if” works but “switch” doesn't work?

// It is simple code

var num = prompt("put number");
// This way is not worked 
switch (num) {
    case num > 0:
        console.log("num++");
        break;
    case num < 0:
        console.log(num-2);
        break;
}
// But this worked
if (num > 0){
    console.log(num++);
} else if (num < 0){
    console.log(num -2);
}

My first way by "switch" is not worked but "if" method worked.我的第一种“switch”方法不起作用,但“if”方法有效。

I tried all of thing for changing code or other ways but the same result.我尝试了所有更改代码或其他方式的方法,但结果相同。

Please guys help me.请大家帮帮我。

Because the statement num > 0 inside you case will return true or false .因为case里面的语句num > 0将返回truefalse If you do this:如果你这样做:

switch (true) {
    case num > 0:
        console.log("num++");
        break;
    case num < 0:
        console.log(num-2);
        break;
}

It will work.它会起作用的。

Cases cannot be expressions, you must normalize your input first. 案例不能是表达式,您必须先规范化您的输入。

Although it is valid to place an expression in a case , in this scenario a more tried-and-true way of dealing with this is to first normalize your input first.尽管在case中放置表达式是有效的,但在这种情况下,一种更可靠的处理方法是首先规范化您的输入。

You can determine direction for example:您可以确定方向,例如:

 var num = parseInt(prompt("put number"), 10); var direction = num < 0? -1: 1; switch (direction) { case 1: console.log("num++"); break; case -1: console.log(num - 2); break; }

The switch acts as a case switcher, meaning you cannot make comparisons to create cases, just list cases by case, and perform some function from this case.该开关充当案例切换器,这意味着您无法进行比较来创建案例,只能逐个列出案例,并从该案例中执行一些 function。 The if / else structure is suitable for making comparisons, as the expected result in the if call is always a boolean. if / else 结构适合进行比较,因为 if 调用中的预期结果始终是 boolean。

Example:例子:

const a = 1;

if (a === 1) {
    console.log('hello');
} else {
    console.log('sad');

switch (a) {
    case 1 : console.log('hello'); break;
    default: console.log('sad'); break;

In your case, I recommend using if/else if/else, as it is more recommended.在您的情况下,我建议使用 if/else if/else,因为更推荐使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM