简体   繁体   中英

switch statement to compare values greater or less than a number

I want to use the switch statement in some simple code i'm writing.

I'm trying to compare the variable in the parenthesis with values either < 13 or >= 13 .

Is this possible using Switch ?

var age = prompt("Enter you age");
switch (age) {
    case <13:
        alert("You must be 13 or older to play");
        break;
    case >=13:
        alert("You are old enough to play");
        break;
}

Directly it's not possible but indirectly you can do this

Try like this

switch (true) {
    case (age < 13):
        alert("You must be 13 or older to play");
        break;
    case (age >= 13):
        alert("You are old enough to play");
        break;
}

Here switch will always try to find true value. the case which will return first true it'll switch to that.

Suppose if age is less then 13 that's means that case will have true then it'll switch to that case.

Instead of switch you can easily to the same thing if else right?

if(age<13)
    alert("You must be 13 or older to play");
else
    alert("You are old enough to play");

Instead of switch use nested if else like this:

if (x > 10) {
    disp ('x is greater than 10') 
}
else if (x < 10){
    disp ('x is less than 10')
}
else
{
    disp ('error')
}

You may use a conditional (ternary) operator instead. It takes a condition followed by a question mark (?), then an expression to execute if the condition is true and another if it is false.

This operator is frequently used as a shortcut for the if statement.

age >= 13 ? "You are old enough to play" : "You must be 13 or older to play";

It might be a bit silly to do this with a switch-case , but I added an answer where using switch-case , just for completeness.

var age = prompt("Enter you age");
switch (age) {
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
    case 11:
    case 12:
        alert("You must be 13 or older to play");
        break;
    default:
        alert("You are old enough to play");
        break;
}

This worked in my case:

var enteredAge = prompt("Enter your age");
let ageMoreThan13 = parseInt(enteredAge) >= 13;
let ageLessThan13 = parseInt(enteredAge) < 13;
switch (ageMoreThan13 || ageLessThan13) {
    case ageLessThan13:
        alert("You must be 13 or older to play");
        break;
     case ageMoreThan13:
        alert("You are old enough to play");
        break;
}

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