简体   繁体   中英

how switch in javascript works when it satisfy all cases condition

switch (true) {
                case (angle<20):
                    console.log("case1")
                    break;

                case (angle<70):
                    console.log("case2")
                    break;

                case (angle<110):
                    console.log("case3")
                    break;

                case (angle<160):
                    console.log("case4")
                    break;
                ... and so on until 360

}

the given code above is working well. i just curious how it able to map out that angle 15 is fall on case 1. while 15 satisfying all case condition

unable to find any clue in google.. so im asking here another topic been raise before. but i dont really get it still some clue here

A switch statement executes the block for the first case that it matches (as per the order the case statements are listed top to bottom).

If that case contains a break , then no other case statements are matched as execution will resume after the switch block.

Because of break; the switch case will break after the angle variable encounters the first case which satisfies the condition.

switch case follow top to bottom approach. So Try reverse condition

switch (true) {
   case (angle>300):
       console.log("case1")
       break;

   case (angle>250):
       console.log("case2")
       break;

   case (angle>200):
       console.log("case3")
       break;

   ... and so on
}

The magic is on the use of the optional break statement, remember this:

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

What happens if you delete the break statements on each case clause?

I think that this quote solve your doubt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM