Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch case with conditions

Am I writing the correct switch case with conditions?

var cnt = $("#div1 p").length; alert(cnt);  switch (cnt) {   case (cnt >= 10 && cnt <= 20):     alert('10');     break;   case (cnt >= 21 && cnt <= 30):     alert('21');     break;   case (cnt >= 31 && cnt <= 40):     alert('31');     break;   default:     alert('>41'); } 

For some reason, the alert does not occur when the conditions are matched!

like image 744
Jasl Avatar asked Apr 23 '10 05:04

Jasl


2 Answers

A switch works by comparing what is in switch() to every case.

switch (cnt) {     case 1: ....     case 2: ....     case 3: .... } 

works like:

if (cnt === 1) ... if (cnt === 2) ... if (cnt === 3) ... 

Therefore, you can't have any logic in the case statements.

switch (cnt) {     case (cnt >= 10 && cnt <= 20): ... } 

works like

if (cnt === (cnt >= 10 && cnt <= 20)) ... 

and that's just nonsense. :)

Use if () { } else if () { } else { } instead.

like image 122
deceze Avatar answered Sep 24 '22 05:09

deceze


You should not use switch for this scenario. This is the proper approach:

var cnt = $("#div1 p").length;  alert(cnt);  if (cnt >= 10 && cnt <= 20) {    alert('10'); } else if (cnt >= 21 && cnt <= 30) {    alert('21'); } else if (cnt >= 31 && cnt <= 40) {    alert('31'); } else  {    alert('>41'); } 
like image 40
rochal Avatar answered Sep 25 '22 05:09

rochal