如果你是一个合格的前端,你是如何实现前端代码优雅化?今天闲来无事单独说下if-else如何实现优雅?
你开发的时候或者修改别人代码的时候,会不会经常看到下面这样案例代码:
if (_this.breadcrumb.length > 1) {
return 1
} else if (_this.breadcrumb.length > 2) {
return 2
} else if (_this.breadcrumb.length > 3) {
return 3
} else if (_this.breadcrumb.length > 4) {
return 4
} else {
return 5
}
这样的代码看着确实有点难受,自己新手时候也有写过,怎么优化呢?如何使这样一段代码,使其===优雅?
来了
第一种简单操作
var a = 1;
if(a){
a = 1;
}else{
a = 0;
};
//可写成
a = a || 0;
第二种三目表达式
var a = 1;
var b = 2;
var c = 3;
var d = 4;
if(a == b){
a = c;
}else{
a = d;
}
//可写成
a = (a == b) ? c : d;
第三种switch…case
switch (status) {
case 1:
sendLog('processing')
jumpTo('IndexPage')
break
case 2:
case 3:
sendLog('fail')
jumpTo('FailPage')
break
default:
sendLog('other')
jumpTo('Index')
}
第四种数组对象映射
const actions = {
'1': ['processing', 'IndexPage'],
'2': ['fail', 'FailPage'],
'3': ['fail', 'FailPage'],
'default': ['other', 'Index']
}// 定义数组对应
const clickHandler = (status) => { // 获取队形数据对象
let action = actions[status] || actions['default'],
LogName = action[0],
pageName = action[1]
sendLog(LogName)
jumpTo(pageName)
}
第五种 map操作
const actions = new Map([
['1', ['processing', 'IndexPage']],
['2', ['fail', 'FailPage']],
['3', ['fail', 'FailPage']],
['default', ['other', 'Index']]
])
const clickHandler = (status) => {
let action = actions.get(status) || actions.get('default')
sendLog(action[0])
jumpTo(action[1])
}
还有其他操作方法,欢迎留言谈论追加。