下面分享 5 種“無痛替代”思路,配合代碼示例,幫你把“面條狀”條件判斷梳理成“魚骨圖”。
1. 一行解決戰(zhàn)斗:三元運算
當邏輯只有兩個結果,并且只是為了給變量賦值時,三元運算符就是濃縮咖啡版 if-else
。
老寫法:
let tip;
if (isVip) {
tip = 0.2;
} else {
tip = 0.1;
}
新寫法:
const tip = isVip ? 0.2 : 0.1;
一行寫完,讀代碼的人再也不用上下翻屏找 else
藏在哪兒。
2. 字典式查找:用對象/Map 做“翻譯表”
當條件多、但每個條件只對應一個固定返回值時,把“判斷”變成“查字典”,既直觀又易擴展。
老寫法:
function getIcon(type) {
if (type === 'pdf') return '??';
if (type === 'img') return '???';
if (type === 'zip') return '???';
return '?';
}
新寫法:
const iconMap = {
pdf: '??',
img: '???',
zip: '???',
};
const getIcon = type => iconMap[type] ?? '?';
新增類型?直接往 iconMap
里添一行鍵值對即可,告別“再寫三行 else if
”。
3. 函數(shù)版策略模式:把“條件”拆成“策略”
如果每個分支里不是返回值,而是一整段動作邏輯,不妨把動作封裝成函數(shù),再按條件調度——這就是輕量級策略模式。
老寫法:
function handle(code) {
if (code === 200) renderDashboard();
else if (code === 401) redirectToLogin();
else if (code === 403) showForbidden();
else showError();
}
新寫法:
const strategies = {
200: renderDashboard,
401: redirectToLogin,
403: showForbidden,
default: showError,
};
const handle = code => (strategies[code] || strategies.default)();
函數(shù)即策略,職責單一,單元測試也方便。
4. 短路運算符:讓條件“隱形”
只想在特定條件下觸發(fā)某個副作用,或者給變量兜底一個默認值?&&
、||
、??
三個符號就能搞定。
“滿足就執(zhí)行”
老寫法:if (debug) console.table(data);
新寫法:
debug && console.table(data);
“兜底默認值”
老寫法:let name; if (inputName) name = inputName; else name = '游客';
新寫法(區(qū)分假值與 null/undefined):
const name = inputName ?? '游客'; // 僅 null/undefined 兜底 // 或 const name2 = inputName || '游客'; // 任何假值都兜底
5. 規(guī)則數(shù)組:把“階梯”變“流水線”
當判斷涉及區(qū)間、權重或更復雜的表達式時,把規(guī)則抽象成數(shù)組,再讓程序按順序匹配第一條命中的規(guī)則——聲明式寫法優(yōu)雅又易擴展。
老寫法:
function shippingFee(weight) {
if (weight <= 1) return 5;
else if (weight <= 5) return 10;
else if (weight <= 10) return 15;
else return 20;
}
新寫法:
const feeRules = [
{ test: w => w <= 1, fee: 5 },
{ test: w => w <= 5, fee: 10 },
{ test: w => w <= 10, fee: 15 },
{ test: () => true, fee: 20 }, // 兜底
];
const shippingFee = weight => feeRules.find(r => r.test(weight)).fee;
新增一個區(qū)間?往數(shù)組頭部插入一條規(guī)則即可,無需改動任何判斷邏輯。
小結
場景 | 推薦方案 |
---|---|
二元賦值 | 三元運算符 |
多值映射 | 對象/Map |
多動作分支 | 函數(shù)映射(策略) |
條件副作用 / 默認值 | 短路運算 |
區(qū)間/權重判斷 | 規(guī)則數(shù)組 |
if-else
本身無罪,但當它開始“橫向生長”時,就該考慮換一種更貼合場景的表達方式。選擇合適的工具,讓代碼自己“說話”,未來的你會感謝今天多敲的這一行重構。