Home > Article > Web Front-end > What does the switch statement in JS do?
The switch statement is a flow control statement, used for multiple selection judgments in js. When the expression value is equal to the set value, the following statement is executed. You can use the break keyword to jump out of the switch statement
Those who have learned the Java language are no stranger to the switch statement. There is also a switch statement in JavaScript speech, and the usage of switch in js is no different from that in java. Next, I will share with you the usage of switch statement in JS
[Recommended course: JavaScript Tutorial】
switch statement
The switch statement is a common flow control statement. The meaning of each case in its statement is: if the expression is equal to this value, the following statement will be executed. The break keyword will cause the code flow to jump out of the switch statement. If the break keyword is omitted, the next case will continue to be executed after the current case is executed. The final default keyword is used to execute code when the expression does not match any of the previous situations.
switch statement usage
switch(变量){ case 变量值1: console.log("a"); //若变量与变量值1相同则执行该处代码 break; case 变量值2: console.log("b"); //若变量与变量值2相同则执行该处代码 break; case 变量值3: console.log("c"); //若变量与变量值3相同则执行该处代码 break; default: console.log("d"); //若变量与所有的变量值不同,则执行该处的代码 }
Example:
<script> function myFunction() { var x; var d=new Date().getDay(); switch (d) { case 0: x="Today it's Sunday"; break; case 1: x="Today it's Monday"; break; case 2: x="Today it's Tuesday"; break; case 3: x="Today it's Wednesday"; break; case 4: x="Today it's Thursday"; break; case 5: x="Today it's Friday"; break; case 6: x="Today it's Saturday"; break; } document.getElementById("demo").innerHTML=x; } </script>
Rendering:
The above is the detailed content of What does the switch statement in JS do?. For more information, please follow other related articles on the PHP Chinese website!