In JavaScript, switch judgments are easy to make mistakes in a detail _ basics

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.