1024programmer Java A detail that is easy to make mistakes in switch judgment in JavaScript_Basic knowledge-js tutorial

A detail that is easy to make mistakes in switch judgment in JavaScript_Basic knowledge-js tutorial

The switch statement is most closely related to the if statement, and 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('Execute case branch');
         break;
     default:
         alert('Execute default branch');
 }

Result:

switch in JS

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('true branch');
 }else{
     alert('false branch');
 }

Result:

switch in JS

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 the congruent mode, which is equivalent to using three equal signs in the if. Let’s rewrite the case code

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:

switch in JS

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('true branch');
 }else{
     alert('false branch');
 }

Result:

switch in JS

Because congruence is used, the string 5 is not equal to the number 5, and a false branch is taken.

The above example illustrates the congruent matching mode used in switch, especially an issue that needs to be paid attention to when matching numbers and strings

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/629646

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索