Home > Web Front-end > JS Tutorial > body text

[JavaScript Tutorial] JavaScript switch statement

黄舟
Release: 2016-12-24 15:11:37
Original
966 people have browsed it

JavaScript switch statement

switch statement is used to perform different actions based on different conditions.

JavaScript switch statement

Use the switch statement to select one of multiple blocks of code to execute.

Syntax

switch(n)
{
case 1:
  执行代码块 1
break;
case 2:
  执行代码块 2
break;
default:
 n 与 case 1 和 case 2 不同时执行的代码
}
Copy after login

How it works: First set the expression n (usually a variable). The value of the expression is then compared with the value of each case in the structure. If there is a match, the code block associated with the case is executed. Please use break to prevent the code from automatically running to the next case.

Example

Show today’s week name. Please note that Sunday=0, Monday=1, Tuesday=2, etc.: The result of

var day=new Date().getDay();
switch (day)
{
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;
}
Copy after login

x is:

Today it's Saturday
Copy after login
Copy after login

default keyword

Please use the default keyword to specify what to do when the match does not exist:

Example

If today is not Saturday or Sunday, the default message will be output:

var day=new Date().getDay();
switch (day)
{
case 6:
  x="Today it's Saturday";
  break;
case 0:
  x="Today it's Sunday";
  break;
default:
  x="Looking forward to the Weekend";
}
Copy after login

x’s running results

Today it's Saturday
Copy after login
Copy after login

The above is the content of the JavaScript switch statement in [JavaScript Tutorial]. For more related content, please pay attention to the PHP Chinese website (www .php.cn)!


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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!