萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 三元運算符進階技巧:從基本語法到函數式編程模式

三元運算符 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';多級分級(建議改用查找表)

實戰優化案例

案例 1:按鈕群組狀態切換(原文靈感)


// 原始 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'));

案例 2:React 條件渲染模式


// ❌ 避免:邏輯混雜 JSX
return (
  
{isLoading ? : error ? : data.map(item => ) }
); // ✅ 推薦:提前返回 + 邏輯分離 if (isLoading) return ; if (error) return ; return ; // ✅ 或:三元用於單一元素屬性

案例 3:TypeScript 類型收窄


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、查找表或策略模式。記住:代碼是給人看的,順便讓機器執行——可讀性永遠優先。

copyright © 萬盛學電腦網 all rights reserved