场景
摆脱
if else
和switch
,条件判断
- 大量枚举值
- 大量配对标识执行不同的方法
普通
单个条件判断
1. 对象法
const codesObj = {
'1': 'xxxxxx',
'2': 'xxxxxx',
'3': 'xxxxxx',
'4': 'xxxxxx',
'5': 'xxxxxx',
'default': 'xxxxxx'
}
const res = codesObj[status] || codesObj['default']
2. Map法
const codesMap = new Map([
[1, 'xxxxxx'],
[2, 'xxxxxx'],
[3, 'xxxxxx'],
[4, 'xxxxxx'],
[5, 'xxxxxx'],
['default', 'xxxxxx']
])
const res = codesMap.get(status) || codesMap.get('default')
使用到Map对象
调用方式
codesMap.get(key)
codesMap()[ 已知序号的index ]
进阶
多个条件同时判断标识
1. 拼接字符对象法
const codesObj = {
[ 'aaa_1', ()=>{/*do sth*/} ],
[ 'aaa_2', ()=>{/*do sth*/} ],
[ 'bbb_3', ()=>{/*do sth*/} ]
}
const func = codesObj[`${identity}_${status}`]
func.call(this)
2. 拼接字符Map法
const codesMap = new Map([
[ 'aaa_1', ()=>{/*do sth*/} ],
[ 'aaa_2', ()=>{/*do sth*/} ],
[ 'bbb_3', ()=>{/*do sth*/} ]
])
const func = codesMap.get(`${identity}_${status}`)
func.call(this)
3. 对象作配对标识Map法
👆这里称map对象,实际上是一个数组。
key
为map[0]
value
为map[1]
这里抛弃get()
的方法,使用filter筛选
和遍历
获取map里的值更灵活
const codesMap = new Map([
[ { identity: 'aaa', status: 1 }, ( ) =>{/*do sth*/} ],
[ { identity: 'bbb', status: 2 }, ( ) =>{/*do sth*/} ]
])
// 筛选符合对象所有属性的项,得到一个map对象数组
const newMaps = [...codesMap].filter( ([key,value])=>{
return ( key.identity == identity && key.status == status)
})
// 正常情况是map对象数组中只有一项,也可以直接 func[0].value.call(this)
newMaps.forEach( ([key,value] ) => {
return value.call(this)
})
但是👆是identity
和status
各不相同对应一个动作函数,当多种情况对应一个动作函数的时候,冗余代码就很多了
常规做法是,把codesMap
写成函数,重复的动作函数存储为变量值
const codesMap = ()=>{
const functionA = ()=>{/*do sth*/}
const functionB = ()=>{/*do sth*/}
return new Map([
[ {identity:'aaa',status:1}, functionA ],
[ {identity:'aaa',status:2}, functionA ],
[ {identity:'bbb',status:3}, functionA ],
[ {identity:'bbb',status:4}, functionA ],
[ {identity:'bbb',status:5}, functionB ],
//...
])
}
// 筛选符合对象所有属性的项,得到一个map对象数组
const newMaps = [...codesMap].filter( ([key,value])=>{
return ( key.identity == identity && key.status == status)
})
// 正常情况是map对象数组中只有一项,也可以直接 func[0].value.call(this)
newMaps.forEach( ([key,value] ) => {
return value.call(this)
})
但是identity
和status
各不相同对应不同的动作函数,而2个变量的值两两配对可能产生出大量的情况,那new Map([..])
里的数组就要大量的写,当然👆已经解决了动作函数冗余的问题
4. 拼接字符+正则Map法
而这种情况,可以考虑使用正则是否更好
正则就不再是以对象为key值做配对标准,而是用上面提到的拼接字符串'aaa_1'
const codesMap = ()=>{
const functionA = ()=>{/*do sth*/}
const functionB = ()=>{/*do sth*/}
return new Map([
[ /^aaa[1-4]$/, functionA ],
[ /^bbb_5$/, functionB ],
//...
])
}
// 用正则test( )筛选对应的maps,得map对象数组
const newMaps = [ ...codesMap() ].filter( ([key,value]) =>{
return ( key.test(`${identity}_${status}`) )
})
newMaps.forEach( ([key,value]) =>{
value.call(this)
})
万事不顺,查文档
Map-MND文档
参考博客-JavaScript复杂判断(if else / switch)的更优雅写法 优化冗余
如有建议和疑问可联系
QQ:1017386624
邮箱:1017386624@qq.com