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

How to use switch in js

下次还敢
下次还敢Original
2024-05-06 14:30:24689browse

The switch statement in JavaScript is a control flow statement used to execute a block of code based on a comparison of an expression with a case label. The syntax is: switch (expression) { case value1: // Code block 1 break; case value2: // Code block 2 break; ... default: // Default code block break; }. The expression is the value to be evaluated, the case label is the value to be compared, the code block is the code to be executed when the expression matches the case label, the break statement is used to jump out of the switch statement, default

How to use switch in js

Usage of switch statement in JavaScript

What is switch statement?

The switch statement is a control flow statement used to compare against multiple case labels based on an expression. When an expression matches a case label, the code block contained in the case label is executed.

Grammar:

<code class="javascript">switch (expression) {
  case value1:
    // 代码块 1
    break;
  case value2:
    // 代码块 2
    break;
  ...
  default:
    // 默认代码块
    break;
}</code>

Usage:

  1. Expression: This is The expression to evaluate, which can be of any type (number, string, boolean, etc.).
  2. case tags: The values ​​of these tags are compared to expressions. Each case label must have a unique value.
  3. Code block: When the expression matches the case label, the corresponding code block will be executed.
  4. break statement: break statement is used to jump out of the switch statement. Without a break statement, it will continue executing the subsequent case.
  5. default label (optional): The default label is used for a block of code that is executed when no case label matches. It can be placed at the end of a switch statement or between other case labels.

Example:

<code class="javascript">// 根据数字选择颜色
switch (num) {
  case 1:
    // 红色
    console.log("红色");
    break;
  case 2:
    // 绿色
    console.log("绿色");
    break;
  case 3:
    // 蓝色
    console.log("蓝色");
    break;
  default:
    // 无效选项
    console.log("无效选项");
    break;
}</code>

Note:

  • Expression must be const or let statement A variable, or a primitive value (such as a number or string).
  • case tag values ​​must be unique and non-repeatable.
  • The break statement is optional, but is typically used to exit a switch statement and prevent subsequent case execution.

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
Previous article:How to add numbers in jsNext article:How to add numbers in js