How to Use the switch expression in js _ javascript tips-js tutorial

Source: Internet
Author: User
Switch expressions are available in many languages, such as java and C waiting. It is easier and clearer to use switch than to use ifelse. The following describes how to use it in detail, if you are interested, refer Preface

The switch expression is available in many languages, such as java and C waiting. It is easier and clearer to use switch than to use if else.

The syntax is simple:

The Code is as follows:


Switch (n)
{
Case 1:
Execution Code Block 1
Break;
Case 2:
Execution Code Block 2
Break;
Default:
Code executed at different times between n and case 1 and case 2
}


The usage of various languages is similar.

In java 1.6 and earlier versions, the variable (n) can only be an integer. The String type is supported after java 7.

In js, the String type can be used directly.

Use instance

The Code is as follows:






New Document

Script
Function funcSwitch (sFlag)
{
Switch (sFlag)
{
Case "Test1 ":
Alert ("Test1 ");
Break;
Case "Test2 ":
Alert ("Test2 ");
Break;
Default :;
}
}

FuncSwitch ("Test2 ");
Script







The logic is simple, and the code is simple. Use string directly to differentiate.

The condition value corresponding to Case is also a variable.

If case is followed by a variable instead of a string. It can be achieved in combination with RegExp.

The Code is as follows:






New Document

Script
Var str1 = "Test1 ";
Var str2 = "Test1 ";
Function funcSwitch (sFlag)
{
Var regExp = new RegExp (sFlag );
Switch (true)
{
Case regExp. test (str1 ):
Alert ("Test1 ");
Break;
Case regExp. test (str2 ):
Alert ("Test2 ");
Break;
Default :;
}
}

FuncSwitch ("Test1 ");

Script





Related Article

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.