简体   繁体   中英

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.

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 . 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.

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. The if / else structure is suitable for making comparisons, as the expected result in the if call is always a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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