jeudi 1 mars 2018

How to Convert IF to SWITCH Statement in JavaScript?

Hello everyone,

First of all thanks in advance for every effort that is going to be provided!

I've been given a task that I have pretty much solved myself

BUT

there is some small correction that needs to be made and I need a help from someone to point me out of where to make some cosmetic changes to my code:

Here is the Task:

Transform the multi-condition if statements sample code into a switch sample code.

var myAge = parseInt( prompt("Enter your age", 30), 10 );

if (myAge >= 0 && myAge <= 10) {

document.write("myAge is between 0 and 10<br />");

}

if ( !(myAge >= 0 && myAge <= 10) ) { document.write("myAge is NOT between 0 and 10<br />");

}

if ( myAge >= 80 || myAge <= 10 ) {

document.write("myAge is 80 or above OR 10 or below<br />");

}

if ( (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) ) { document.write("myAge is between 30 and 39 or myAge is " + "between 80 and 89");

}
<DOCTYPE html>

<html lang="en"> <head>

<title>SOME CODE</title> </head>

<body> 

</body> 

</html>

So the Result by Default under the age 30 is:

myAge is NOT between 0 and 10 myAge is between 30 and 39 or myAge is

between 80 and 89

Here is what I'm done so far:

                        var myAge = parseInt( prompt("Enter your age", 30), 10 );  // Get the user's response, converted to a number
                        switch (true) {        // Switch statement if the condition is True
                        case myAge >= 0 && myAge <= 10:  // Check the inputs value in range 0 - 10                     
                             document.write("myAge is between 0 and 10<br/>"); break;
                        case ( !(myAge >= 0 && myAge <= 10) ): // Check the inputs value if it's not a in range between 0 - 10 ( !(myAge >= 0 && myAge <= 10) )
                 document.write("myAge is NOT between 0 and 10<br/>"); break;
                        case myAge >= 80 || myAge <= 10: // Check the inputs value if it's greater/equal to 80 OR less/equal to 10
                             document.write("myAge is 80 or above OR 10 or below<br/>"); break;
                        default :
                             document.write("myAge is between 30 and 39 or myAge is " + "between 80 and 89");// Check the inputs value in range 30 - 39 And 80 - 89 
                           
                        }
<DOCTYPE html>

<html lang="en"> <head>

<title>Chapter 3, Example 2</title> </head>

<body>

</body> 

</html>

And, as you can see that the result is slightly different. I got printed just this:

myAge is NOT between 0 and 10

I know the solution is simple anough BUT unfortunately I cannot solve it so that it will print a:

myAge is NOT between 0 and 10 myAge is between 30 and 39 or myAge is

as well.

Please, someone, help me so sovle it I would really apreciate it!

Aucun commentaire:

Enregistrer un commentaire