We're writing JS Code time , It is often encountered that the logic judgment is complex . Normally , It can be used if/else or switch
To realize multiple conditional judgments , But there's a problem : As the complexity of logic increases , In code if/else and switch It will become more and more bloated . This article will take you to try to write more elegant judgment logic .

For example, the following code :
const onButtonClick = (status) => { if (status == 1) { sendLog('processing')
jumpTo('IndexPage') } else if (status == 2) { sendLog('fail')
jumpTo('FailPage') } else if (status == 3) { sendLog('fail') jumpTo('FailPage')
} else if (status == 4) { sendLog('success') jumpTo('SuccessPage') } else if
(status == 5) { sendLog('cancel') jumpTo('CancelPage') } else {
sendLog('other') jumpTo('Index') } }
You can see the click logic of this button in the code . Do two things according to the activity status , Send the embedded point of the log and jump to the corresponding page . It's easy to think that this code can be used switch Rewrite as follows :
const onButtonClick = (status) => { switch (status) { case 1:
sendLog('processing') jumpTo('IndexPage') break case 2: case 3: sendLog('fail')
jumpTo('FailPage') break case 4: sendLog('success') jumpTo('SuccessPage') break
case 5: sendLog('cancel') jumpTo('CancelPage') break default: sendLog('other')
jumpTo('Index') break } }
ok , Looks like if/else A clearer hierarchy , Careful readers may also have found a trick :case 2 and case 3
When the logic of , You can omit the previous logic processing code ,case 2 Will automatically execute and case 3 Logic of .

however , There's a simpler way of writing :
const actions = { '1': ['processing', 'IndexPage'], '2': ['fail', 'FailPage'],
'3': ['fail', 'FailPage'], '4': ['success', 'SuccessPage'], '5': ['cancel',
'CancelPage'], default: ['other', 'Index'], } const onButtonClick = (status) =>
{ let action = actions[status] || actions['default'], logName = action[0],
pageName = action[1] sendLog(logName) jumpTo(pageName) }

The code above does look clean , The subtlety of this approach is , It takes the judgment condition as the attribute name of the object , Treat the processing logic as the attribute value of the object . When you click the button , This method is especially suitable for single condition judgment , That is to say, logical judgment is carried out through the way of object attribute search .

This is a good way , But is there any other way to code it ? yes , we have !
const actions = new Map([ [1, ['processing', 'IndexPage']], [2, ['fail',
'FailPage']], [3, ['fail', 'FailPage']], [4, ['success', 'SuccessPage']], [5,
['cancel', 'CancelPage']], ['default', ['other', 'Index']], ]) const
onButtonClick = (status) => { let action = actions.get(status) ||
actions.get('default') sendLog(action[0]) jumpTo(action[1]) }
use Map replace Object There are many advantages ,Map The difference between object and common object is :

* An object usually has its own prototype , So an object always has one “prototype” key
* The key of an object can only be a string or symbol , but Map The key of can be any value
* You can use size Properties are easy to get Map Number of key value pairs in , However, the number of key value pairs in an object cannot be obtained directly
Now let's upgrade the difficulty of this problem . When the button is clicked , Not only to judge the state , And determine the identity of the user .
const onButtonClick = (status, identity) => { if (identity == 'guest') { if
(status == 1) { //do sth } else if (status == 2) { //do sth } else if (status
== 3) { //do sth } else if (status == 4) { //do sth } else if (status == 5) {
//do sth } else { //do sth } } else if (identity == 'master') { if (status ==
1) { //do sth } else if (status == 2) { //do sth } else if (status == 3) { //do
sth } else if (status == 4) { //do sth } else if (status == 5) { //do sth }
else { //do sth } } }
As you can see from the example above , When your logic escalates to double judgment , Your judgment will double , Your code will double .

How to make the code cleaner ?

Here's a solution .
const actions = new Map([ ['guest_1', () => {}], ['guest_2', () => {}],
['guest_3', () => {}], ['guest_4', () => {}], ['guest_5', () => {}],
['master_1', () => {}], ['master_2', () => {}], ['master_3', () => {}],
['master_4', () => {}], ['master_5', () => {}], ['default', () => {}], ]) const
onButtonClick = (identity, status) => { let action =
actions.get(`${identity}_${status}`) || actions.get('default')
action.call(this) }
The core logic of the above code is . Concatenate two judgment conditions into a string as Map Key of , Then directly query the value of the corresponding string when querying . of course , We can also put Map Change to
Object.
const actions = { guest_1: () => {}, guest_2: () => {}, //.... } const
onButtonClick = (identity, status) => { let action =
actions[`${identity}_${status}`] || actions['default'] action.call(this) }
If the reader finds it a bit awkward to put the query together as a string , There's another solution , That's using one Map Object as key.
const actions = new Map([ [{ identity: 'guest', status: 1 }, () => {}], [{
identity: 'guest', status: 2 }, () => {}], //... ]) const onButtonClick =
(identity, status) => { let action = [...actions].filter(([key, value]) =>
key.identity == identity && key.status == status) action.forEach(([key, value])
=> value.call(this)) }
You can also see here Map Differences from common objects , among Map You can use any type of data as a key . Now let's make it a little more difficult . If for guest In terms of identity , state
1-4 The processing logic of is the same ?

This is the worst case scenario ( A lot of code repetition ):
const actions = new Map([ [{ identity: 'guest', status: 1 }, () => {}], [{
identity: 'guest', status: 2 }, () => {}], [{ identity: 'guest', status: 3 },
() => {}], [{ identity: 'guest', status: 4 }, () => {}], [{ identity: 'guest',
status: 5 }, () => {}], //... ])
A better way is to separate the processing logic functions :
const actions = () => { const functionA = () => {} const functionB = () => {}
return new Map([ [{ identity: 'guest', status: 1 }, functionA], [{ identity:
'guest', status: 2 }, functionA], [{ identity: 'guest', status: 3 },
functionA], [{ identity: 'guest', status: 4 }, functionA], [{ identity:
'guest', status: 5 }, functionB], //... ]) } const onButtonClick = (identity,
status) => { let action = [...actions()].filter(([key, value]) => key.identity
== identity && key.status == status) action.forEach(([key, value]) =>
value.call(this)) }
This is enough for everyday needs , But seriously , function A Quoted 4 second , Still a little annoying .

If things really get complicated , For example, identity 3 species , The status is 10 species , You need to define 30 Processing logic , Many of the processing logic is the same , It seems unacceptable .

And you can do that :
const actions = () => { const functionA = () => {} // Logical processing A const functionB =
() => {} // Logical processing B return new Map([ [/^guest_[1-4]$/, functionA], [/^guest_5$/,
functionB], //... ]) } const onButtonClick = (identity, status) => { let action
= [...actions()].filter(([key, value]) => key.test(`${identity}_${status}`))
action.forEach(([key, value]) => value.call(this)) }
Use at this time Map instead of Object The advantages are obvious , Because we can use regular form as key .

If demand becomes : All right guest All operations need to send a log burying point , In different states guest There may be different logical processes , So we can write it as follows :
const actions = () => { const functionA = () => {} // Logical processing A const functionB =
() => {} // Logical processing B const functionC = () => {} // Send log C return new Map([
[/^guest_[1-4]$/, functionA], [/^guest_5$/, functionB], [/^guest_.*$/,
functionC], //... ]) } const onButtonClick = (identity, status) => { let action
= [...actions()].filter(([key, value]) => key.test(`${identity}_${status}`))
action.forEach(([key, value]) => value.call(this)) }
thus , Common logic and single logic can be executed at the same time .

summary

This article talks about eight kinds of JS The writing method of logical judgment , include :

* if/else
* switch
* Single judgment : store in Object in
* Single judgment : store in Map In object
* Multiple judgment : Concatenate conditions into a string , store in Object in
* Multiple judgment : Concatenate conditions into a string , store in Map In object
* Multiple judgment : Store conditions as objects in Map in
* Multiple judgment : Write the condition as regular and store it in Map in
Share today , May your future coding life be more than just if/else or switch.

Technology
©2019-2020 Toolsou All rights reserved,
JS How to operate java Realize the function of grabbing red packets C Language programming to find a student's grade The United Nations 《 Glory of Kings 》 Please go to the studio : To save the earth Dialogue between apple and Nissan suspended ,Apple Car How's it going ?CSS architecture design China's longest high speed rail officially opened ! The fastest way to finish the race 30.5 hour First knowledge MySQL Comprehensive review ( dried food )2021 year 1 Monthly programmer salary statistics , average 14915 element How to use it quickly html and css Write static page