We have a,b,c,d four different categories, at the very beginning there are only three categories, and two categories are doing the same thing:
1 function Categoryhandle (category) {2 if (Category!== ' A ') {3 console.log (' B, C '); 4 Else {5 console.log (' A '); 6 }7 }
1.1
Then there is the category d--it has a different task compared to B and C, and it has a similar task to B and C. As a result, the code becomes this way.
function Categoryhandle (category) { if(category!== ' A ') { if(category = = = ' D ') ) { console.log (' D '); Else { console.log (' b,c '); } Console.log (' B, C, D ') Else { console.log (' A ');} }
1.2
And then
function Categoryhandle (category) { if(category = = = ' A ') { console.log (' a '); Else if (category = = = ' B ') { console.log (' B '); Else if (category = = = ' C ') { console.log (' D '); } Else if (category = = = ' d ') { console.log (' d ');} }
1.3
Of course I do it with a switch statement, but I really don't want to think that. Next, JavaScript's artifice to do the job:
functionCategoryhandlerefactor (category) {varCategoryaction = { A: {run:function() {Console.log (A) } }, B: {run:function() {Console.log (B) } }, C: {run:function() {Console.log (C) } }, D: {run:function() {Console.log (D) } } }; Categoryaction[category].run ();}
1.4
js-ifelse-Artifice