Switch statements are most closely related to if statements, and are commonly used in other programming languages as a flow control statement, but switch matching is congruent mode, if you do not pay attention to the details of the program will often error.
Code:
var n = ' 5 ';
Switch (n) {case
5:
alert (' Execute Case branch ');
break;
Default:
alert (' Execute Default branch ');
}
Results:
Many people may mistakenly think that the above program will take the case branch, the result is gone the default branch. Aren't they two equal? We use the IF statement to see.
Code:
var n = ' 5 ';
if (n==5) {
alert (' true branch ');
} else{
alert (' Fake branch ');
}
Results:
Can match in the IF statement, but why not in the switch statement?
This is because the case in the switch statement uses the congruent pattern and is equivalent to using the three equals sign in the IF. We'll rewrite the code for the case.
Code:
var n = ' 5 ';
Switch (n) {case
' 5 '://Rewrite original case 5 to case ' 5 '
alert (' Execute Case branch ');
break;
Default:
alert (' Execute Default branch ');
}
Results:
If you rewrite it, you'll be able to go to the case branch, just like we use three full equals in the IF.
Code:
var n = ' 5 ';
if (n===5) {
alert (' true branch ');
} else{
alert (' Fake branch ');
}
Results:
Because the use of congruent, so string 5 is not equal to the number 5, the result went false branch.
The above example shows that the strict matching pattern is used in the switch, especially when the number matches the string.