如果使用傳統(tǒng)的 if-else 語句,對復(fù)雜的條件進(jìn)行邏輯判斷,代碼很容易變得冗長難維護(hù),分享幾種替代的寫法。
1. 對象映射替代 if-else
傳統(tǒng)寫法
functiongetPrice(user) {
if (user.type === 'vip') {
return'VIP價格';
} elseif (user.type === 'svip') {
return'SVIP價格';
} elseif (user.type === 'vvip') {
return'VVIP價格';
} else {
return'普通價格';
}
}
替代寫法
const priceStrategy = {
vip: () => 'VIP價格',
svip: () => 'SVIP價格',
vvip: () => 'VVIP價格',
default: () => '普通價格'
};
functiongetPrice(user) {
return (priceStrategy[user.type] || priceStrategy.default)();
}
2. Array.includes 替代多條件
傳統(tǒng)寫法
if (status === 'failed' || status === 'error' || status === 'rejected') {
handleError();
}
替代寫法
const errorStatus = ['failed', 'error', 'rejected'];
if (errorStatus.includes(status)) {
handleError();
}
3. 三元運(yùn)算符鏈?zhǔn)绞褂?/span>
傳統(tǒng)寫法

替代寫法

4. && 和 || 運(yùn)算符巧用

5. Switch 模式匹配

6. 使用 Proxy 進(jìn)行條件攔截

7. 函數(shù)式編程方法

8. 狀態(tài)機(jī)模式

9. 使用裝飾器處理?xiàng)l件
functioncheckPermission(target, name, descriptor) {
const original = descriptor.value;
descriptor.value = function(...args) {
if (this.user?.hasPermission) {
return original.apply(this, args);
}
thrownewError('No permission');
};
return descriptor;
}
classDocument {
@checkPermission
edit() {
// 編輯文檔
}
}
歡迎補(bǔ)充。
閱讀原文:原文鏈接
該文章在 2025/10/17 17:36:30 編輯過