Home  >  Article  >  Web Front-end  >  [JavaScript Tutorial] JavaScript switch statement

[JavaScript Tutorial] JavaScript switch statement

黄舟
黄舟Original
2016-12-24 15:11:37966browse

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 不同时执行的代码
}

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;
}

x is:

Today it's Saturday

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";
}

x’s running results

Today it's Saturday

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


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