2、switch/case
- /**
- * 按钮点击事件
- * @param {number} status 活动状态:1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消
- */
- 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
- }
- }
这样看起来比if/else清晰多了,细心的同学也发现了小技巧,case 2和case 3逻辑一样的时候,可以省去执行语句和break,则case 2的情况自动执行case 3的逻辑。
3、存放到Object
将判断条件作为对象的属性名,将处理逻辑作为对象的属性值,在按钮点击的时候,通过对象属性查找的方式来进行逻辑判断,这种写法特别适合一元条件判断的情况。
- const actions = {
- '1': ['processing','IndexPage'],
- '2': ['fail','FailPage'],
- '3': ['fail','FailPage'],
- '4': ['success','SuccessPage'],
- '5': ['cancel','CancelPage'],
- 'default': ['other','Index'],
- }
- /**
- * 按钮点击事件
- * @param {number} status 活动状态:1开团进行中 2开团失败 3 商品售罄 4 开团成功 5 系统取消
- */
- const onButtonClick = (status)=>{
- let action = actions[status] || actions['default'],
- logName = action[0],
- pageName = action[1]
- sendLog(logName)
- jumpTo(pageName)
- }
4、存放到Map
- const actions = new Map([
- [1, ['processing','IndexPage']],
- [2, ['fail','FailPage']],
- [3, ['fail','FailPage']],
- [4, ['success','SuccessPage']],
- [5, ['cancel','CancelPage']],
- ['default', ['other','Index']]
- ])
- /**
- * 按钮点击事件
- * @param {number} status 活动状态:1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消
- */
- const onButtonClick = (status)=>{
- let action = actions.get(status) || actions.get('default')
- sendLog(action[0])
- jumpTo(action[1])
- }
(编辑:ASP站长网)
|