Optimization of condition judgment statements in javascript

Source: Internet
Author: User

Optimization of condition judgment statements in javascript

No matter what program you write, conditional statements are usually used, such:if...else... switchTo determine the conditions. Here is a piece of code:

Function abc (test) {if (test = 1) {console. log (the value of 'test is '+ test);} else if (test = 2) {console. log (the value of 'test is '+ test);} else if (test = 3) {console. log (the value of 'test is '+ test);} else if (test = 4) {console. log (the value of 'test is '+ test);} abc (1); abc (2); abc (3); abc (4 );

The result is 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.1 s]

In fact, there is no problem in code development at ordinary times, but many times we want our code to become elegant and easy to understand, and minimize repeated code. For the above problem, there isswitchTo replace this manyifStatement judgment.

The optimized code is as follows:

Function bcd (test) {switch (test) {case 1: console. log (the value of 'test is '+ test); break; case 2: console. log (the value of 'test is '+ test); break; default: console. log ('test value is null');} bcd (); bcd (1 );

The result is as follows:

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

Is there any better way to do this in js? With the features of js objects, you can easilyswitchThe 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');}) ();} dcf (); dcf ('Dog ');

I am the default value
Dog

Here, we mainly use two knowledge points: 1. js to get the object attribute value 2.||Operator value.

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.