示例
const fn = (nBoolean) {
if (nBoolean) {
return 1
} else {
return 2
}
}
1、三元运算符
做一些简单的判断,因为多层嵌套的三元运算符也不具备良好的可读性
const fn = (nBoolean) {
reuturn nBoolean ? 1 : 2
}
2、switch case
对于switch case,虽然他的可读性确实比else if更高,但是书写起来比较麻烦
let type = 'A'
//if else if
if (type === 'A' || type === 'B') {
console.log(1);
} else if (type === 'C') {
console.log(2);
} else if(type === 'D') {
console.log(3);
} else {
console.log(0)
}
//switch case
switch (type) {
case 'A':
case 'B':
console.log(1)
break
case 'C':
console.log(2)
break
case 'D':
console.log(3);
break;
default:
console.log(0)
}
3、对象配置/策略模式
对象配置看起来跟 策略模式 差不多,都是根据不同得参数使用不同得数据/算法/函数。😺
策略模式就是将一系列算法封装起来,并使它们相互之间可以替换。被封装起来的算法具有独立性,外部不可改变其特性。
案例1 商场促销价
// 获取折扣 --- 使用if else
const getDiscount = (userKey) => {
if (userKey === '普通会员') {
return 0.9
} else if (userKey === '年费会员') {
return 0.85
} else if (userKey === '超级会员') {
return 0.8
} else {
return 1
}
}
console.log(getDiscount('普通会员')) // 0.9
// 获取折扣 -- 使用对象配置/策略模式
const getDiscount = (userKey) => {
// 我们可以根据用户类型来生成我们的折扣对象
let discounts = {
'普通会员': 0.9,
'年费会员': 0.85,
'超级会员': 0.8,
'default': 1
}
return discounts[userKey] || discounts['default']
}
console.log(getDiscount('普通会员')) // 0.9
对象配置不一定非要使用对象去管理我们键值对,还可以使用 Map去管理
// 获取折扣 -- 使用对象配置/策略模式
const getDiscount = (userKey) => {
// 我们可以根据用户类型来生成我们的折扣对象
let discounts = new Map([
['普通会员', 0.9],
['年费会员', 0.85],
['超级会员', 0.8],
['default', 1]
])
return discounts.get(userKey) || discounts.get('default')
}
console.log(getDiscount('普通会员')) // 0.9