Home > Web Front-end > JS Tutorial > What does the switch statement in JS do?

What does the switch statement in JS do?

清浅
Release: 2019-01-31 11:32:51
Original
6233 people have browsed it

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

What does the switch statement in JS do?

[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");  //若变量与所有的变量值不同,则执行该处的代码
}
Copy after login

Example:

<script>
function myFunction()
{
var x;
var d=new Date().getDay();
switch (d)
  {
  case 0:
    x="Today it&#39;s Sunday";
    break;
  case 1:
    x="Today it&#39;s Monday";
    break;
  case 2:
    x="Today it&#39;s Tuesday";
    break;
  case 3:
    x="Today it&#39;s Wednesday";
    break;
  case 4:
    x="Today it&#39;s Thursday";
    break;
  case 5:
    x="Today it&#39;s Friday";
    break;
  case 6:
    x="Today it&#39;s Saturday";
    break;
  }
document.getElementById("demo").innerHTML=x;
}
</script>
Copy after login

Rendering:

What does the switch statement in JS do?

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template