如何优雅地搞定多个判断,别告诉我你只会if-else和switch

最近在弄个人网站,开始更系统的思考一些优雅写法,之前工作中经常运用到的多状态操作

最开始是这样写,写好一个, 其他复制粘贴,虽然直接,但是代码块略微庞大,这种简单赋值尚且如此,更不用说其他复杂操作了

let room = this.$route.path.split('/').splice(-1).join()
let current = 0
if(room === 'porch'){
   current=1
}else if(room === 'living') {
    current=2
}else if(room === 'dining') {
    current=3
}else if(room === 'study') {
    current=4
}else if(room === 'happy') {
    current=5
}else if(room === 'balcony') {
    current=6
}else if(room === 'bedroom') {
    current=7
}else if(room === 'washroom') {
    current=8
}

后来对于这种简单的 我就改成switch了

 let room = this.$route.path.split('/').splice(-1).join()
 let current      
 switch(room){
    case 'porch':
        current=1
        break
    case 'living':
        current=2
        break
    case 'dining':
        current=3
        break
    case 'study':
        current=4
        break
    case 'happy':
        current=5
        break
    default:
        current=0
        break
 }

但是依然觉得有点low呀,人生还是要不断尝试,果然还是有更好的方式,
 

let room = this.$route.path.split('/').splice(-1).join()
let item = {
  'porch': [1], // 之所以用数组是为了方便加其他参数与操作
  'living': [2],
  'dining':[3],
  'study': [4],
  'happy': [5],
  'balcony': [6],
  'default':[0]
}


let current = 0
const roomEvent= (room) => {
  let action = item [room] || item ['default']
  current = action[0] 
	
}
// 调用传参即可
roomEvent(room)

最后,还可以继续尝试……

比如Map,Map优点很多,在这里比较有用的是Map 的键可以是任何值

let room = this.$route.path.split('/').splice(-1).join()
let item = new Map({
  ['porch', [1]], // 之所以用数组是为了方便加其他参数与操作
  ['living', [2]],
  ['dining',[3]],
  ['study', [4]],
  ['happy', [5]],
  ['balcony', [6]],
  ['default',[0]]
})


let current = 0
const roomEvent= (room) => {
  let action = item.get(room) || item.get('default')
  current = action[0] 
}
roomEvent(room)

对于我来说,到这种程度已经足够了,面对更为复杂的逻辑,我看大牛还可以用正则匹配,更适合那种比较规律的状态码,不过我这里不太适合。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值