Switch case with conditions

前端 未结 8 1678
情深已故
情深已故 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:25

    Ok it is late but in case you or someone else still want to you use a switch or simply have a better understanding of how the switch statement works.

    What was wrong is that your switch expression should match in strict comparison one of your case expression. If there is no match it will look for a default. You can still use your expression in your case with the && operator that makes Short-circuit evaluation.

    Ok you already know all that. For matching the strict comparison you should add at the end of all your case expression && cnt.

    Like follow:

    switch(mySwitchExpression)
    case customEpression && mySwitchExpression: StatementList
    .
    .
    .
    default:StatementList
    

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

    p1

    p2

    p3

    p3

    p4

    p5

    p6

    p7

    p8

    p9

    p10

    p11

    p12

提交回复
热议问题