[JavaScript tutorial] JavaScriptswitch statement

Source: Internet
Author: User
The switch statement is used to execute different actions based on different conditions.

JavaScript switch statement

The switch statement is used to execute different actions based on different conditions.

JavaScript switch statement

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

Syntax

Switch (n) {case 1: Execution Code Block 1 break; case 2: Execution Code Block 2 break; default: Code executed differently between n and case 1 and case 2}

Working principle: first set expression n (usually a variable ). Then the expression value is compared with the value of each case in the structure. If a match exists, the code block associated with the case will be executed. Use break to prevent code from automatically running to the next case.

Instance

The name of the day of the week is displayed. Please note that Sunday = 0, Monday = 1, Tuesday = 2, and so on:

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 running result:

Today it's Saturday

Default keyword

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

Instance

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

Running result of x

Today it's Saturday

The above is the content of the JavaScript switch statement in the [JavaScript tutorial]. For more information, see the PHP Chinese website (www.php1.cn )!


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.