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