switch - accidentally made a mistake

When writing the code, in order to save trouble, I wrote this line:

switch(n){

case 1:

console.log(1);

break;

case 2||3||4:

(In order to save trouble, because the same code block is executed when 2, 3, and 4)

console.log(222);

break;

case 1:

console.log(1);

break;

default:

}

As a result, when n=2 or 3 or 4, the result is all 1. Confused. Still an online question.

Later found the reason:

The case should be followed by a variable. When n is 2, 3, 4, the result of (2||3||4) is true. case true is equivalent to case 1.

For convenience, you can write it like this:

case 2:

case 3:

case 4:

console.log(222)

As long as it does not break out, the code will continue to execute according to the current conditions .

A mistake, blame yourself for being too careless!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325906143&siteId=291194637