“Switch” statement

Switch statements can replace multiple if judgments.

The switch statement provides a more descriptive way of selecting multiple branches.

grammar

The switch statement has at least one case code block and an optional default code block.

Something like this:

switch(x) {
  case 'value1':  // if (x === 'value1'). [break]

  case 'value2':  // if (x === 'value2'). [break]

  default:... [break]}Copy the code
  • To comparexThe value is the same as the first onecase(i.e.value1) is strictly equal, and then compare the secondcase(value2) and so on.
  • If it’s equal,switchThe statement executes accordinglycaseCode block until the nearest one is encounteredbreakStatement (or untilswitchStatement end).
  • If no case matches, the case is executeddefaultCode block (ifdefaultPresent).

For example

Switch example (execute case 4 part) :

let a = 2 + 2;

switch (a) {
  case 3:
    alert( 'Too small' );
    break;
  case 4:
    alert( 'Exactly! ' );
    break;
  case 5:
    alert( 'Too large' );
    break;
  default:
    alert( "I don't know such values" );
}
Copy the code

The switch here compares the value of A from the first case branch to the value after case, which is 3.

And then we compare 4. Matches, so execute from case 4 until the nearest break is encountered.

If there is nobreakThe program will proceed to the next one without any checkscase.

Example without break:

let a = 2 + 2;

switch (a) {
  case 3:
    alert( 'Too small' );
  case 4:
    alert( 'Exactly! ' );
  case 5:
    alert( 'Too big' );
  default:
    alert( "I don't know such values" );
}
Copy the code

In the example above we see three alerts executed consecutively:

alert( 'Exactly! ' );
alert( 'Too big' );
alert( "I don't know such values" );
Copy the code

Any expression can beswitch/caseThe parameters of the

Both switch and case allow arbitrary expressions.

Such as:

let a = "1";
let b = 0;

switch (+a) {
  case b + 1:
    alert("this runs, because +a is 1, exactly equals b+1");
    break;

  default:
    alert("this doesn't run");
}
Copy the code

Here +a returns 1, which is compared to b + 1 in case, and executes the corresponding code.


“Case” group

Several case branches that share the same code can be grouped into a group:

For example, if we want case 3 and Case 5 to execute the same code:

let a = 2 + 2;

switch (a) {
  case 4:
    alert('Right! ');
    break;

  case 3: // (*) The following two cases are grouped together
  case 5:
    alert('Wrong! ');
    alert("Why don't you take a math class?");
    break;

  default:
    alert('The result is strange. Really.');
}
Copy the code

Now both 3 and 5 display the same information.

Switch /case has the ability to “group” by case, which is a side effect of switch statements without breaks. Since there is no break, case 3 will execute from line (*) to case 5.

Type matters

Again, equality here is strict equality. The values being compared must be of the same type for a match to occur.

For example, let’s look at the following code:

let arg = prompt("Enter a value?")
switch (arg) {
  case '0':
  case '1':
    alert( 'One or zero' );
    break;

  case '2':
    alert( 'Two' );
    break;

  case 3:
    alert( 'Never executes! ' );
    break;
  default:
    alert( 'An unknown value')}Copy the code
  1. inpromptDialog input0,1, the firstalertPop up.
  2. The input2And the secondalertPop up.
  3. But the input3Because thepromptThe result is a string"3"Is not strictly equal= = =Of a numeric type3, socase 3No execution! socase 3Part is a piece of invalid code. So it will executedefaultBranch.

Homework assignments

Do the questions yourself and then look at the answers.

1. Rewrite the “switch” structure to “if” structure

Importance: ⭐️⭐ ⭐️⭐️

Write the code for the following “switch” structure as if.. The else structure:

switch (browser) {
  case 'Edge':
    alert( "You've got the Edge!" );
    break;

  case 'Chrome':
  case 'Firefox':
  case 'Safari':
  case 'Opera':
    alert( 'Okay we support these browsers too' );
    break;

  default:
    alert( 'We hope that this page looks ok! ' );
}
Copy the code

2. Rewrite the “if” structure to “switch” structure

Degree of importance: ⭐️⭐️ ️⭐

Rewrite the following code with switch:

let a = +prompt('a? '.' ');

if (a == 0) {
  alert( 0 );
}
if (a == 1) {
  alert( 1 );
}

if (a == 2 || a == 3) {
  alert( '2, 3' );
}
Copy the code

The answer:

Reply 1-2-13 in the background of wechat public account “Technology Chat” to obtain the answer to this question.


Modern JavaScript Tutorials: Open source modern JavaScript tutorials from beginner to advanced quality. React provides a JavaScript tutorial for MDN learners.

Read for free online: zh.javascript.info


Scan the QR code below and follow the wechat public account “Technology Chat” to subscribe for more exciting content.