views:

584

answers:

4

Am I writing the correct switch case?

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!

+4  A: 

what you are doing is to look for (0) or (1) results.

(cnt >= 10 && cnt <= 20) returns either true or false.

--edit-- you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length. --edit--

Kind Regards

--Andy

jAndy
Andy you probably have a point here that I cld not follow..mind rewording that? what am i doing wrong?
Jasl
you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length.
jAndy
additional info on `switch()` http://www.w3schools.com/js/js_switch.asp
Reigel
A: 

This should work with this :

var cnt = $("#div1 p").length;

            switch (true) {
                case (cnt >= 10 && cnt <= 20):
                    alert('10');
                    break;
                case (cnt >= 21 && cnt <= 30):
                   alert('21');
                    break;
                case (cnt >= 31 && cnt <= 40):
                    break;
                default:
                    alert('>41');
            }
Fabien Ménager
that is perverted code
jAndy
I didn't say this is a good code ;) And switch permits this. This is like when you write `if ( 2 == myVar) `
Fabien Ménager
+1  A: 

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.

deceze
+2  A: 

GUYS, seriously, some of the answers here should send you back to the high-school. Why would you use switch here?

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');
}
rochal