The switch statement is most closely related to the if statement, and is also a process control statement commonly used in other programming languages. However, the switch matches are congruent patterns. If you do not pay attention to this detail, you will often make mistakes when writing programs.
Code:
var n = '5';switch(n){case 5:alert('Execute case branch');break;default:alert('Execute default branch');}result:
Many people may mistakenly think that the above program will go to the case branch, but in the end, it will go to the default branch. Are they not equal? Let's use the if statement to see.
Code:
var n = '5';if(n==5){alert('true branch');}else{alert('false branch');}result:
It can be matched in an if statement, but why can't it be matched in a switch statement?
This is because the case in the switch statement uses convergence mode, which is equivalent to the use of three equal signs in if. Let's rewrite the code of the case
Code:
var n = '5';switch(n){case '5': // Rewrite the original case 5 into case '5'alert('Execute case branch');break;default:alert('Execute default branch');}result:
After rewriting it, you can go to the case branch, just like we use three equal signs in if
Code:
var n = '5';if(n===5){alert('true branch');}else{alert('false branch');}result:
Because convergence is used, string 5 does not equal the number 5, and the false branch is gone.
The above example shows that a problem that needs to be paid attention to when using a congruent matching pattern in switch, especially when numbers match strings.