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