Optimization of conditional judgment statements in JavaScript

Source: Internet
Author: User

No matter what program to write, usually use conditional statements, such as: if...else... switch Such statements, to achieve the judgment of the conditions. A piece of code looks like this:

 function ABC(test){    if(Test = =1){console.log (' value of ' test ' is ' +test '); }    Else if(Test = =2){console.log (' value of ' test ' is ' +test '); }    Else if(Test = =3){console.log (' value of ' test ' is ' +test '); }    Else if(Test = =4){console.log (' value of ' test ' is ' +test '); }}ABC (1); ABC (2); ABC (3); ABC (4);

The results are as follows:

The value of test is 1
The value of test is 2
The value of test is 3
The value of test is 4
[Finished in 0.1s]

In fact, in the normal development of code this is not a problem, but a lot of time we want to be able to become elegant and easy to understand the code, and as little as possible to reduce the duplication of code. For the above problems, there is one in JS switch to replace such a multi- if sentence judgment.

The optimized code is as follows:

function bcd(test){    switch(test){        case1:            console.log(‘test的值是‘+test);            break;        case2:            console.log(‘test的值是‘+test);            break;        default:            console.log(‘test的值是null‘);    }}bcd();bcd(1);

The results are as follows:

The value of test is null
The value of test is 1

So is there a better way to do it in JS? The use of JS object features can be easily switch optimized, the code is as follows:

 function DCF(test){    return({cat: function(){Console.log (' Cat '}, Dog: function(){Console.log (' dog '), Zhiqiang: function(){Console.log (' Zhiqiang ');} }[test] | | function(){Console.log (' I am the default value ');} )();} DCF ();d CF (' dog ');

I am the default value
Dog

Here the main function is to two knowledge points: 1.js Gets the value of the object property 2. || The problem with the value of the operator.

Optimization of conditional judgment statements in JavaScript

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.