javascript怎么复杂判断吗?

javascript怎么复杂判断?下面本篇文章给大家介绍一下javascript复杂判断的几种写法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

JavaScript复杂判断优雅的写法

#按钮点击事件 status活动状态

例如:1:开团进行中,2:开团失败,3:商品售空,4:开团成功,5:系统取消

第一种写法:

第一种写法 if else 判断 代码多但是逻辑清晰

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

  }

}

第三种写法:将判断条件作为对象的属性名,将处理逻辑作为对象的属性值。

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])
}

更多web前端知识,请查阅 HTML中文网 !!

以上就是javascript怎么复杂判断吗?的详细内容,更多请关注易知道|edz.cc其它相关文章!

推荐阅读