我们编写js代码时经常遇到复杂逻辑判断的情况,通常大家可以用if/else或者switch来实现多个条件判断,但这样会有个问题,随着逻辑复杂度的增加,代码中的if/else/switch会变得越来越臃肿,越来越看不懂,那么如何更优雅的写判断逻辑,本文带你试一下。
/**
* 按钮点击事件
* @param {number} status 活动状态:1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消
*/
const onButtonClick = (status) => {
if (status == 1) {
sendLog('processing') jumpTo('IndexPage')
} else if (status == 2) {
sendLog('fail') jumpTo('FailPage')
} else if (status == 3) {
sendLog('fail') jumpTo('FailPage')
} else if (status == 4) {
sendLog('success') jumpTo('SuccessPage')
} else if (status == 5) {
sendLog('cancel') jumpTo('CancelPage')
} else {
sendLog('other') jumpTo('Index')
}
}
通过代码可以看到这个按钮的点击逻辑:根据不同活动状态做两件事情,发送日志埋点和跳转到对应页面,大家可以很轻易的提出这段代码的改写方案,switch出场:
const onButtonClick = (status) => {
switch (status) {
case 1:
sendLog('processing')
jumpTo('IndexPage')
break
case 2:
case 3:
sendLog('fail')
jumpTo('FailPage')
break
case 4:
sendLog('success')
jumpTo('SuccessPage')
break
case 5:
sendLog('cancel')
jumpTo('CancelPage')
break
default:
sendLog('other')
jumpTo('Index')
break
}
}
/**
* 按钮点击事件
* @param {number} status 活动状态:1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消
*/
const onButtonClick = (status) => {
if (status == 1) {
sendLog('processing') jumpTo('IndexPage')
} else if (status == 2) {
sendLog('fail') jumpTo('FailPage')
} else if (status == 3) {
sendLog('fail') jumpTo('FailPage')
} else if (status == 4) {
sendLog('success') jumpTo('SuccessPage')
} else if (status == 5) {
sendLog('cancel') jumpTo('CancelPage')
} else {
sendLog('other') jumpTo('Index')
}
}
通过代码可以看到这个按钮的点击逻辑:根据不同活动状态做两件事情,发送日志埋点和跳转到对应页面,大家可以很轻易的提出这段代码的改写方案,switch出场:
const onButtonClick = (status) => {
switch (status) {
case 1:
sendLog('processing')
jumpTo('IndexPage')
break
case 2:
case 3:
sendLog('fail')
jumpTo('FailPage')
break
case 4:
sendLog('success')
jumpTo('SuccessPage')
break
case 5:
sendLog('cancel')
jumpTo('CancelPage')
break
default:
sendLog('other')
jumpTo('Index')
break
}
}









