Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
363 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...