在开发过程中,遇到的多种相似的逻辑判断,会造成臃肿的 if else 代码结构不够清晰
利用对象来实现 if else 的逻辑判断
将判断条件作为对象的属性名,将处理逻辑作为属性值,通过对象属性查找的方式来进行逻辑判断,这种写法特别适合一元条件判断的情况。
const actions = {
'1': ['processing','IndexPage'],
'2': ['fail','FailPage'],
'3': ['success','SuccessPage'],
'4': ['cancel','CancelPage'],
'default': ['other','Index'],
}
const onButtonClick = (status)=>{
let action = actions[status] || actions['default'],
logName = action[0],
pageName = action[1]
doSomething(logName)
Jump(pageName)
}
使用ES6的map,好处:
- Map可以用任何类型的数据作为key
- 可以通过size属性很容易地得到一个Map的键值对个数,而对象的键值对个数只能手动确认
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])
}
多个判断条件的情况
把两个条件拼接成字符串,并通过以条件拼接字符串作为键,以处理函数作为值的Map对象进行查找并执行
const actions = new Map([
['guest_1', ()=>{/*do sth*/}],
['guest_2', ()=>{/*do sth*/}],
['guest_3', ()=>{/*do sth*/}],
['master_1', ()=>{/*do sth*/}],
['master_2', ()=>{/*do sth*/}],
['master_3', ()=>{/*do sth*/}],
['default', ()=>{/*do sth*/}],
])
const onButtonClick = (identity,status)=>{
let action = actions.get(`${identity}_${status}`) || actions.get('default')
action.call(this)
}
或者使用对象的作为key
const actions = new Map([
[{identity:'guest',status:1},()=>{/*do sth*/}],
[{identity:'guest',status:2},()=>{/*do sth*/}],
[{identity:'master',status:1},()=>{/*do sth*/}],
[{identity:'master',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))
}