三元運算符 condition ? exprIfTrue : exprIfFalse 是 JavaScript 唯一的三元運算子,正確使用能大幅提升程式碼簡潔度與可讀性。本文從基礎語法進階到函數式模式、物件屬性動態存取、渲染邏輯、TypeScript 類型收窄,並列出濫用反模式。
// if-else 等價
const result = condition ? valueIfTrue : valueIfFalse;
// 等價於
let result;
if (condition) result = valueIfTrue;
else result = valueIfFalse;
| 模式 | 程式碼範例 | 適用場景 |
|---|---|---|
| 基本賦值 | const status = isOnline ? 'online' : 'offline'; | 簡單二元狀態 |
| 函數呼叫分派 | isAdmin ? renderAdminPanel() : renderUserPanel(); | 邏輯分支執行不同函數 |
| 動態屬性存取 | obj[isActive ? 'activate' : 'deactivate'](); | 方法名由條件決定 |
| 動態類別名 | el.className = 'btn ' + (primary ? 'btn-primary' : 'btn-secondary'); | CSS 類別切換 |
| 物件屬性條件包含 | const config = { baseUrl: '/api', ...(isProd ? { timeout: 5000 } : {}) }; | 條件式展開屬性 |
| 陣列條件包含 | const items = [a, b, ...(showC ? [c] : [])]; | 條件式展開元素 |
| 提前返回 | if (!user) return redirect('/login'); → return user ? renderDashboard() : redirect('/login'); | Guard Clause 風格 |
| 巢狀三元(慎用) | score >= 90 ? 'A' : score >= 80 ? 'B' : 'C'; | 多級分級(建議改用查找表) |
// 原始 if-else
function turn(action) {
const $item = $(this).closest('li');
const $target = action === 'prev' ? $item.prev() : $item.next();
$target.addClass('has-img');
$item.removeClass('has-img');
}
// 三元優化:動態屬性存取
function turn(action) {
const $item = $(this).closest('li');
const $target = $item[action === 'prev' ? 'prev' : 'next']();
$target.addClass('has-img');
$item.removeClass('has-img');
}
// 綁定
$('#nextBtn').on('click', () => turn('next'));
$('#prevBtn').on('click', () => turn('prev'));
// ❌ 避免:邏輯混雜 JSX
return (
{isLoading ? :
error ? :
data.map(item => )
}
);
// ✅ 推薦:提前返回 + 邏輯分離
if (isLoading) return ;
if (error) return ;
return
;
// ✅ 或:三元用於單一元素屬性
function format(value: string | number | null) {
// 三元運算符配合類型守衛
return value != null
? (typeof value === 'number' ? value.toFixed(2) : value.toUpperCase())
: 'N/A';
}
// TypeScript 自動收窄:value 為 string | number 在第一分支,null 在第二分支
| 反模式 | 問題 | 重構建議 |
|---|---|---|
多層巢狀 a ? b : c ? d : e | 右結合性導致難讀,JS 與 PHP/Python 行為不同 | 改用 if/else if/else、查找表、策略模式 |
副作用塞入三元 cond ? doA() : doB() | 語意模糊,難除錯 | 改用 if (cond) doA(); else doB(); |
超長表達式 cond ? veryLongExpr : anotherLongExpr | 行寬超標、難維護 | 提取變數、提取函數 |
條件重複計算 expensive() ? expensive() : fallback | 效能浪費、副作用風險 | 先存變數 const v = expensive(); v ? v : fallback |
// ❌ 多層三元分級
const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';
// ✅ 查找表(O(1)、易擴充、可配置化)
const GRADE_THRESHOLDS = [
{ min: 90, label: 'A' },
{ min: 80, label: 'B' },
{ min: 70, label: 'C' },
{ min: 0, label: 'F' }
];
const grade = GRADE_THRESHOLDS.find(t => score >= t.min)?.label ?? 'F';
// ✅ 更進階:分數區間映射函數
const getGrade = (score) =>
score >= 90 ? 'A' :
score >= 80 ? 'B' :
score >= 70 ? 'C' : 'F'; // 只有 3-4 層時可接受
三元運算符是「表達式導向」編程的利器,適合單一條件、純值計算、屬性/類別動態切換、提前返回。超過兩層巢狀、包含副作用、邏輯複雜時,請毫不猶豫改用 if/else、switch、查找表或策略模式。記住:代碼是給人看的,順便讓機器執行——可讀性永遠優先。