Monday, May 20, 2024
37
rated 0 times [  41] [ 4]  / answers: 1 / hits: 18087  / 8 Years ago, sun, july 24, 2016, 12:00:00

It is my first time using the switch statement in Javascript. Is there a way to evaluate multiple conditions one switch statement, like so:



var i = 1;
switch(i && random(1)<0.3) {
case (1):
//code block
break;
case (2):
//code block
}


So that the code blocks would execute if both of the conditions were true?


More From » switch-statement

 Answers
8

You could do something like this:



var i = 1;
switch((i==1) + (Math.random(1)<0.3)*2) {
case 0:
//code block when neither is true
break;
case 1:
//code block when only i == 1
break;
case 2:
//code block when only random(1)<0.3
break;
case 3:
//code block when both i==1 and random(1)<0.3
break;
}


... but it is not really the nicest code, and can easily lead to mistakes when one of the tested expressions is anything else than 0 or 1 (false or true).



It is better to use if ... else constructs to deal with this:



var i = 1;
var small = Math.random(1)<0.3;
if (i==1) {
if (small) {
//code block when both i==1 and random(1)<0.3
} else {
//code block when only i == 1
}
} else if (small) {
//code block when only random(1)<0.3
} else {
//code block when neither is true
}

[#61265] Thursday, July 21, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shamya

Total Points: 38
Total Questions: 101
Total Answers: 96

Location: Thailand
Member since Thu, Apr 22, 2021
3 Years ago
;