当前位置:网站首页>JS multiple judgment writing
JS multiple judgment writing
2022-06-13 02:42:00 【Zixuan Pavilion】
JavaScript A more elegant way of writing complex judgments
Abstract : Writing code is an art .
original text :JavaScript A more elegant way of writing complex judgments
author :Think.
Fundebug Reprint by authorization , The copyright belongs to the original author .
Premise
We write js Code often encounter complex logical judgment , Usually you can use if/else perhaps switch To achieve multiple conditional judgments , But there's a problem , As the complexity of logic increases , In code if/else/switch It will become more and more bloated , More and more can't understand , So how to write judgment logic more elegantly , This article will show you a try .
for instance
Let's start with a piece of code
/** * Button click event * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The goods are sold out 4 The opening was successful 5 System cancel */
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 through the code : Do two things according to different activities , Send log burying point and jump to corresponding page , You can easily put forward the rewriting scheme of this code ,switch appearance :
/** * Button click event * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The goods are sold out 4 The opening was successful 5 System cancel */
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
}
}
Um. , It looks better than if/else It's much clearer , Careful students have also found some tips ,case 2 and case 3 When the logic is the same , The execution statement and break, be case 2 Automatic execution of case 3 The logic of .
At this time, some students will say , 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'],
}
/** * Button click event * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The goods are sold out 4 The opening was successful 5 System cancel */
const onButtonClick = (status)=>{
let action = actions[status] || actions['default'],
logName = action[0],
pageName = action[1]
sendLog(logName)
jumpTo(pageName)
}
The code above does look cleaner , The clever thing about this method is : Take the judgment condition as the attribute name of the object , Treat the processing logic as the property value of the object , When the button is clicked , Through the way of object attribute search to make logical judgment , This kind of writing is especially suitable for the case of monistic condition judgment .
Is there any other way of writing ? 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']]
])
/** * Button click event * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The goods are sold out 4 The opening was successful 5 System cancel */
const onButtonClick = (status)=>{
let action = actions.get(status) || actions.get('default')
sendLog(action[0])
jumpTo(action[1])
}
It uses es6 Inside Map object , Is it better ?Map Objects and Object What's the difference between objects ?
An object usually has its own prototype , So an object always has a ”prototype” key .
The key of an object can only be a string or Symbols, But a Map The bond of can be any value .
You can go through size Property easily gets a Map Number of key value pairs of , The number of key value pairs of an object can only be confirmed manually .
We need to escalate the problem , Previously, when a button was clicked, only judgment was needed status, Now we need to determine the identity of users :
/** * Button click event * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The opening was successful 4 The goods are sold out 5 There is inventory but not a group * @param {string} identity Identification :guest Objective state master The dominant state */
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
}
}
}
Forgive me for not writing the specific logic in every judgment , Because the code is too long .
Forgive me for using if/else, Because I see a lot of people still using if/else Write this large logical judgment .
From the example above, we can see that , When your logic is upgraded to binary judgment , Your judgment will double , Your code will double , At this time how to write more relaxed ?
const actions = new Map([
['guest_1', ()=>{
/*do sth*/}],
['guest_2', ()=>{
/*do sth*/}],
['guest_3', ()=>{
/*do sth*/}],
['guest_4', ()=>{
/*do sth*/}],
['guest_5', ()=>{
/*do sth*/}],
['master_1', ()=>{
/*do sth*/}],
['master_2', ()=>{
/*do sth*/}],
['master_3', ()=>{
/*do sth*/}],
['master_4', ()=>{
/*do sth*/}],
['master_5', ()=>{
/*do sth*/}],
['default', ()=>{
/*do sth*/}],
])
/**javascript * Button click event * @param {string} identity Identification :guest Objective state master The dominant state * @param {number} status Activity status :1 The opening is in progress 2 The opening of the group failed 3 The opening was successful 4 The goods are sold out 5 There is inventory but not a group */
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 conditions into a string , And through the conditional splicing string as a key , With a processing function as a value Map Object to find and execute , This kind of writing is especially useful when judging multiple conditions .
Of course, if the above code is used Object Object to implement is similar :
const actions = {
'guest_1':()=>{
/*do sth*/},
'guest_2':()=>{
/*do sth*/},
//....
}
const onButtonClick = (identity,status)=>{
let action = actions[`${
identity}_${
status}`] || actions['default']
action.call(this)
}
If some students think it's a bit awkward to spell the query criteria into a string , There's another way , Just use Map object , With Object Object as key:
c
onst actions = new Map([
[{
identity:'guest',status:1},()=>{
/*do sth*/}],
[{
identity:'guest',status:2},()=>{
/*do sth*/}],
//...
])
const onButtonClick = (identity,status)=>{
let action = [...actions].filter(([key,value])=>(key.identity == identity && key.status == status))
action.forEach(([key,value])=>value.call(this))
}
Is it a little more advanced ?
It can also be seen here Map And Object The difference between ,Map You can use any type of data as key.
Let's upgrade the difficulty a little bit now , If guest Under the circumstances ,status1-4 The processing logic is the same , The worst case scenario is :
const actions = 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 */}],
//...
])
A good way to write this is to cache the processing logic functions :
const actions = ()=>{
const functionA = ()=>{
/*do sth*/}
const functionB = ()=>{
/*do sth*/}
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 , It's rewritten up here 4 Time functionA Still a little upset , If the judgment conditions become particularly complicated , such as identity Yes 3 States ,status Yes 10 States , Then you need to define 30 Processing logic , And often many of these logics are the same , This seems to be what I don't want to accept , That can be done in this way :
const actions = ()=>{
const functionA = ()=>{
/*do sth*/}
const functionB = ()=>{
/*do sth*/}
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))
}
here Map The advantages of , You can use regular types as key 了 , In this way, there is infinite possibility , If demand becomes , Anyone who guest In case of any situation, send a log burial point , Different status The situation also needs a separate logical treatment , Then we can write like this :
const actions = ()=>{
const functionA = ()=>{
/*do sth*/}
const functionB = ()=>{
/*do sth*/}
const functionC = ()=>{
/*send log*/}
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))
}
That is to say, using the characteristics of array loop , Logic that meets the regular criteria is executed , Then you can execute both common logic and individual logic , Because of the existence of regularity , You can open your imagination to unlock more ways to play , This article will not go over .
summary
This article has taught you 8 A kind of logical judgment , Include :
if/else
switch
One dollar judgment : Deposit in Object in
One dollar judgment : Deposit in Map in
When making multiple judgments : take condition Concatenate into a string and save it to Object in
When making multiple judgments : take condition Concatenate into a string and save it to Map in
When making multiple judgments : take condition Save as Object Deposit in Map in
When making multiple judgments : take condition Writing is saved to Map in
thus , This article will also come to an end , May you live in the future , It's not just that if/else/switch.
边栏推荐
- [data analysis and visualization] key points of data drawing 11- precautions for radar chart
- How can intelligent safe power distribution devices reduce the occurrence of electrical fire accidents?
- For loop instead of while loop - for loop instead of while loop
- Microsoft Pinyin opens U / V input mode
- Ffmpeg principle
- Introduction to facial expression recognition system -- offline environment configuration
- [reading papers] comparison of deeplobv1-v3 series, brief review
- [deep learning] fast Reid tutorial
- [reading papers] visual convolution zfnet
- Welcome to blog navigation
猜你喜欢
![[data analysis and visualization] key points of data drawing 4- problems of pie chart](/img/e1/618ff53b33b4b1de6acf4942130c17.jpg)
[data analysis and visualization] key points of data drawing 4- problems of pie chart

Data processing in detailed machine learning (II) -- Feature Normalization
![[reading point paper] deeplobv3+ encoder decoder with Atlas separable revolution](/img/24/decef903cd618bf7bb7fea635ee62e.jpg)
[reading point paper] deeplobv3+ encoder decoder with Atlas separable revolution
![[data and Analysis Visualization] data operation in D3 tutorial 3-d3](/img/c9/82385b125a8e47d900c320b5f4f3b2.jpg)
[data and Analysis Visualization] data operation in D3 tutorial 3-d3

OneNote使用指南(一)

Data warehouse notes | 5 factors that need attention for customer dimension modeling

Uni app Foundation

Branch and bound method, example sorting

Detailed explanation of UCI datasets and their data processing (with 148 datasets and processing codes attached)

Fast Color Segementation
随机推荐
OneNote User Guide (1)
[reading papers] deepface: closing the gap to human level performance in face verification. Deep learning starts with the face
01 initial knowledge of wechat applet
nn. Conv2d and nn Convtranspose2d differences
Rounding in JS
Exam23 named windows and simplified paths, grayscale conversion
Opencvsharp4 handwriting recognition
[data and Analysis Visualization] D3 introductory tutorial 1-d3 basic knowledge
[data analysis and visualization] key points of data drawing 11- precautions for radar chart
vant实现移动端的适配
[common tools] pyautogui tutorial
Change the topic of change tax
An image is word 16x16 words: transformers for image recognition at scale
Svg filter effect use
[reading papers] transformer miscellaneous notes, especially miscellaneous
[data analysis and visualization] key points of data drawing 6- too many data groups
Opencvsharp4 pixel read / write and memory structure of color image and gray image
How did you spend your winter vacation perfectly?
SANs证书生成
[data analysis and visualization] key points of data mapping 7- over mapping