Home > Web Front-end > JS Tutorial > A detail that is easy to make mistakes in switch judgment in JavaScript_Basic knowledge

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

WBOY
Release: 2016-05-16 16:38:29
Original
1389 people have browsed it

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分支');
}
Copy after login

Result:

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

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('假 分支');
}
Copy after login

Result:

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

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分支');
}
Copy after login

Result:

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

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('假 分支');
}
Copy after login

Result:

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

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template