Why Switch statement only working with true keyword?

后端 未结 3 538
情书的邮戳
情书的邮戳 2021-01-22 20:33

Can anyone explain to me why first one is not working and second one is working?

First Statement

function test(n) {
    switch (n) {
    case (n         


        
3条回答
  •  别那么骄傲
    2021-01-22 21:08

    switch uses strict comparison.

    You take a number in the switch statement and in cases, just comparsions which return a boolean value.

    A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using strict comparison, ===) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.) If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.

提交回复
热议问题