The switch statement is most closely related to the if statement. It is also a flow control statement commonly used in other programming languages. However, the matching of switch is congruent mode. If you do not pay attention to this detail, you will often make errors when writing programs.
Code:
var n = '5'; switch(n){ case 5: alert('执行case分支'); break; default: alert('执行default分支'); }
Result:
Many people may mistakenly think that the above program will take the case branch, but in the end it takes the default branch. Aren't they two equal? Let's take a look using the if statement.
Code:
var n = '5'; if(n==5){ alert('真 分支'); }else{ alert('假 分支'); }
Result:
It can match in the if statement, but why can’t it match in the switch statement?
This is because the case in the switch statement uses congruent mode, which is equivalent to using three equal signs in if. Let’s rewrite the case code
Code:
var n = '5'; switch(n){ case '5': // 把原来的 case 5 改写成 case '5' alert('执行case分支'); break; default: alert('执行default分支'); }
Result:
After rewriting, you can take the case branch, just like we use three congruent signs in if
Code:
var n = '5'; if(n===5){ alert('真 分支'); }else{ alert('假 分支'); }
Result:
Because congruence is used, the string 5 is not equal to the number 5, and the result is a false branch.
The above example shows that the congruent matching mode is used in switch, especially an issue that needs to be paid attention to when matching numbers and strings