如何优雅实现if else功能

88 阅读1分钟

if else

if( a === 1) {
  // TODO 
} else if ( a === 2 ) {
  // TODO
} else if ( a === 3) {
  // TODO
} else {
  // TODO
}

swich case

...

对象写法代替

const handler = {
  0: () => { console.log('00000000000000') },
  1: () => { console.log('11111111111111') },
  2: () => { console.log('22222222222222') },
  default: () => { console.log('333333333333333') }
}
const onhandler = (state = 0) => {
  const action = handler[state] || handler['default']
  // action.call(this)
  action()
}
onhandler(2)

new Map

const handler = new Map([
  [0, () => { console.log('00000000000000') }],
  [1, () => { console.log('11111111111111') }],
  [2, () => { console.log('22222222222222') }],
  ['default', () => { console.log('AAAAAAAAAAAAAAA') }]
])

const onhandler = (status = 0) => {
  const action = handler.get(status) || handler.get('default')
  action.call(this)
}
onhandler(3)

map 扩展

const handler = new Map([
  ['短途', '#FFEDED'],
  ['长途', '#EDFFF9'],
  ['夜间行驶', '#EDEEFF'],
  ['default', '#ead2f1']
])
return handler.get(value) || handler.get('default')

const handler = new Map([
  [1, { code: 602, msg: `账号或密码不正确` }],
  [2, { code: 601, msg: `账号或密码不正确` }],
  [0, { code: 600, msg: `查无此人` }]
])
return handler.get(authResult.code) || handler.get(0)