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!
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.
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'); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With