Optimization of condition judgment statements in javascript
No matter what program you write, conditional statements are usually used, such:if...else...
switch
To 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 isswitch
To replace this manyif
Statement 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 easilyswitch
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');}) ();} 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.