1. 对象映射替代 if-else
传统写法
function getPrice(user) {
if (user.type === 'vip') {
return 'VIP价格';
} else if (user.type === 'svip') {
return 'SVIP价格';
} else if (user.type === 'vvip') {
return 'VVIP价格';
} else {
return '普通价格';
}
}
替代写法
const priceStrategy = {
vip: () => 'VIP价格',
svip: () => 'SVIP价格',
vvip: () => 'VVIP价格',
default: () => '普通价格'
};
function getPrice(user) {
return (priceStrategy[user.type] || priceStrategy.default)();
}
2. Array.includes 替代多条件
传统写法
if (status === 'failed' || status === 'error' || status === 'rejected') {
handleError();
}
替代写法
const errorStatus = ['failed', 'error', 'rejected'];
if (errorStatus.includes(status)) {
handleError();
}
3. 三元运算符链式替代传统if else
const store = 91;
const messgae = store >= 90 ? "优秀" :
store >= 80 ? "良好" :
store >= 60 ? "及格" : "不及格";