Switch case with conditions

前端 未结 8 1697
情深已故
情深已故 2020-12-01 02:36

Am I writing the correct switch case?

var cnt = $(\"#div1 p\").length;
                alert(cnt);
                switch (cnt) {
                    case (c         


        
8条回答
  •  醉话见心
    2020-12-01 03:31

    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.

提交回复
热议问题