0
how to design switch condition in JavaScript Thanks
if the cases are range, may I use "0<a<5" as a case condition? ::>_<:: I tried and it only check if a<5. so the minus checking should be in another case or a range can be a casa condition but I make some syntax errors〒_〒l var a=-6 switch (true){ case 0<a<5: alert(1) break; Case a>=5: Alert(2) Break;.....} ~(*+﹏+*)~
3 Réponses
+ 4
suppose a are integers between 0, 1, 2, 3... 8, 9
to separate 1 - 4 from others
the code snippet should be
switch (a) {
case 0:
console.log('a is 0');
break;
case 1:
case 2:
case 3:
case 4:
console.log('0<a<5');
break;
case 5:
case 6:
case 7:
case 8:
console.log('4<a<9');
break;
case 9:
console.log('a is 9');
break;
default:
console.log('Invalid value of a');
}
https://code.sololearn.com/WLUw7woWzCB8/?ref=app
1. break; is used to separate conditions.
2. Put the variables in the parentheses after switch
See?
+ 4
yes switch is for discrete cases, for example, integers.
If the variable will lie within a range, you need to use if-else statements, sometimes nested if necessary
if (kpi<0){
console.log("error");
}else{
if(kpi<90){
console.log("small");
}else{
if(kpi<200){
console.log("large");
}else{
console.log("abnormal");
}
}
}
suppose you have two valid range, you need to handle the out-of-boundary values as well.
0
https://love2dev.com/blog/javascript-switch-statement/
according to the KPI example in this page, the case can be KPI>=90 bigger or equal, but my case 0<a<5 is not accepted. There is also the method mentioned by Gordon, thanks and it is perfect for limit number of cases.
my BMI code
https://code.sololearn.com/WTSL2hwKrpqP/?ref=app