在表单或者某些场景下我们通常需要对输入的值进行很多次的校验/判断 , 我们可以通过将条件语句对象化的方式来优化我们的代码

1
2
3
4
5
6
7
8
9
10
11
12
//优化之前
const exampleO = (param) => {
if(param === 1){
return 'is 1'
}else if(param === 2){
return 'is 2'
}else if(param === 3){
return 'is 3'
}else{
return null
}
}

1
2
3
4
5
6
7
8
9
//优化之后
const exampleT = (param) => {
const conditionMap = {
1:'is 1',
2:'is 2',
3:'is 3',
}
return conditionMap[param] || null
}