Y
Y
Yaroslav Ryzhenko2016-12-03 21:16:44
JavaScript
Yaroslav Ryzhenko, 2016-12-03 21:16:44

Why doesn't the switch statement work in my case?

This code works:

var a = (prompt("Введите число от 1-го до 30-ти:"));
    if(a >= 1 && a <= 10 || a >= 21 && a <= 30) {
    alert("Не попал!");
    }
    
    else if(a >= 11 && a <= 20) {
    alert("Попал!");
    }
    
    else {
    alert("Вы ввели число больше 30-ти или не число.");
    }

This code doesn't work:
var a = (prompt("Введите число от 1-го до 30-ти:"));
switch(a) {
        case a >= 1 && a <= 10 || a >= 21 && a <= 30:
        alert("Не попал!");
        break;
    
        case a >= 11 && a <= 20:
        alert("Попал!");
        break;
    
        default: 
        alert("Вы ввели число больше 30-ти или не число.");
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Decadal, 2016-12-03
@0rislav

Because in the case, the value of the expression is first calculated and then compared with the parameter. In this case, you have a predicate in case (a function that returns a boolean result). Accordingly, switch will check whether a is a variable with a boolean value. But it is not. And it won't work. Try passing a as true and you'll see exactly how switch works. It will print 'failed' because when the first case is evaluated, the parameter a will be cast to 1 and pass the condition >= 1 && <= 10
You don't need switch in this case

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question