Home >Web Front-end >JS Tutorial >How to use the JavaScript Switch statement in action

How to use the JavaScript Switch statement in action

jacklove
jackloveOriginal
2018-05-04 11:22:252196browse

You will often encounter Switch statement when you start learning javascript. Here we will explain in detail the actual use of Switch statement.

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

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

Today it's Friday

default keyword

Please use the default keyword to Specifies what to do when a 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 Result:

Looking forward to the Weekend

The switch statement is a sibling of the if statement. This section introduces the usage of switch statement and its difference from switch statement in Java.

For more knowledge about JavaScript Switch statement, please read the relevant content of php Chinese website:

Related recommendations:

Ajax PHP JavaScript MySQL implementation Simple no-refresh online chat room

The relationship between JavaScript calling mode and this keyword binding

In-depth understanding of JavaScript event mechanism

The above is the detailed content of How to use the JavaScript Switch statement in action. For more information, please follow other related articles on the PHP Chinese website!

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