
如果使用传统的 if-else 语句,对复杂的条件进行逻辑判断,代码很容易变得冗长难维护,分享几种替代的写法。
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. 三元运算符链式使用传统写法

替代写法





