Home >Web Front-end >JS Tutorial >How to use switch in js

How to use switch in js

下次还敢
下次还敢Original
2024-05-01 08:18:17646browse

The switch statement in JavaScript is used to execute a specific block of code based on the variable value: compare the variable value and the case value. When matching, execute the corresponding code block and use break to exit. Executes the default block (optional) when there is no match.

How to use switch in js

The use of switch statement in JavaScript

The switch statement is used in JavaScript to compare the values ​​of variables and execute the corresponding Conditional statements for code blocks. The syntax is as follows:

<code class="javascript">switch (expression) {
  case value1:
    // 当 expression 的值等于 value1 时执行的代码
    break;
  case value2:
    // 当 expression 的值等于 value2 时执行的代码
    break;
  ...
  default:
    // 当 expression 的值与所有 case 不匹配时执行的代码
}</code>

Instructions for use:

  1. expression: The variable or expression to be compared.
  2. value1, value2,...: The value to be compared with expression.
  3. case: Indicates the value to be compared.
  4. break: Indicates exiting the switch statement when the case ends.
  5. default (optional): The code block that is executed when the value of expression matches all cases.

How it works:

  1. JavaScript compares the value of expression to the value of each case.
  2. If a match is found, the corresponding code block is executed.
  3. If no match is found, the default code block is executed (if it exists).

Example:

<code class="javascript">let grade = 'A';

switch (grade) {
  case 'A':
    console.log('优秀');
    break;
  case 'B':
    console.log('良好');
    break;
  case 'C':
    console.log('及格');
    break;
  default:
    console.log('不及格');
}</code>

Output:

<code>优秀</code>

Please note that the break statement is necessary to prevent the switch statement from executing subsequently case is crucial, without break the code will continue executing for all matching cases.

The above is the detailed content of How to use switch in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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