萬盛學電腦網

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

JavaScript 實用技巧大全:布爾陷阱、三元運算符、短路邏輯、字串構建、DOM 遍歷優化

一、布爾值陷阱與真假判斷

Falsy 值(僅 8 個)


false, 0, -0, 0n, '', null, undefined, NaN

其餘皆為 Truthy(包括 `'0'`、`[]`、`{}`、`new Date()`、`function(){}`)。

常見誤區

表達式結果原因
Boolean('0')true非空字串
'0' == truefalse'0'→1, true→1, 但 '0'==true 為 false(類型轉換規則)
0 == []true[]→''→0
[] == falsetrue[]→''→0, false→0
{} == falsefalse{}→'[object Object]'→NaN ≠ 0

最佳實踐

  • 檢查「非空/非零/非假」:直接 `if (val)`
  • 嚴格判斷 `null/undefined`:`if (val != null)`(等同 `val !== null && val !== undefined`)
  • 區分 `0`/`''`/`false`:用 `===` 或 `Object.is()`

二、條件(三元)運算符


// 替代 if/else 返回值
const result = condition ? valueIfTrue : valueIfFalse;

// 適用於 JSX/模板字串
const html = `
${name}
`; // 巢狀三元(慎用,超過兩層改用函數/物件查找) const status = loading ? '載入中' : error ? '錯誤' : data ? '成功' : '空';

三、短路邏輯運算符(&&、||、??)

||:預設值模式


// 舊寫法
function foo(opt) { var win = opt || window; }

// 現代:nullish coalescing (??) 僅在 null/undefined 時回退
function foo(opt) { const win = opt ?? window; }
// 差異:'' || 'default' → 'default',但 '' ?? 'default' → ''

&&:防禦性存取


// 舊寫法
if (user && user.profile && user.profile.avatar) { ... }

// 現代:可選鏈 ?.
const avatar = user?.profile?.avatar;

// 短路執行副作用(慎用,降低可讀性)
isLoggedIn && renderUserPanel();

??:空值合併(ES2020)


const config = {
  timeout: userConfig.timeout ?? 5000,
  retries: userConfig.retries ?? 3
};

四、高效字串構建

陣列 join(舊環境最佳)


function listHtml(items) {
  const html = [];
  for (let i = 0; i < items.length; i++) {
    html[i] = itemHtml(items[i]); // 直接賦值比 push 快
  }
  return '
    ' + html.join('') + '
'; }

模板字面量(現代首選)


const html = items.map(item => `
  • ${escapeHtml(item.name)}
  • `).join(''); // 或 const html = `
      ${items.map(item => `
    • ${escapeHtml(item.name)}
    • `).join('')}
    `;

    效能對比(10,000 項)

    方法耗時
    字串 += 迴圈~45ms
    陣列 push + join~3ms
    陣列直接賦值 + join~2ms
    模板字面量 map + join~4ms

    五、DOM 節點列表遍歷優化

    避免重複存取 length

    
    // ❌ 慢:每次迴圈存取 length(即時 NodeList 需重新計算)
    for (let i = 0; i < paragraphs.length; i++) { ... }
    
    // ✅ 快:快取 length
    const len = paragraphs.length;
    for (let i = 0; i < len; i++) { ... }
    
    // ✅ 更快:迭代器模式(陣列化後)
    for (const p of paragraphs) { ... }
    // 或
    [...paragraphs].forEach(p => ...);
    

    樹狀遍歷:firstChild/nextSibling

    
    for (let child = parent.firstChild; child; child = child.nextSibling) {
      if (child.nodeType === 1) { // Element 節點
        doSomething(child);
      }
    }
    
    • 避免 `childNodes` 即時列表陷阱
    • 比 `querySelectorAll` 更省記憶體(無需建立陣列)
    • 適合大量節點、深度樹遍歷

    六、其他實用片段

    物件深度凍結

    
    function deepFreeze(obj) {
      Object.freeze(obj);
      Object.keys(obj).forEach(key => {
        if (typeof obj[key] === 'object' && !Object.isFrozen(obj[key])) {
          deepFreeze(obj[key]);
        }
      });
      return obj;
    }
    

    防抖與節流

    
    // 防抖:連續觸發僅最後一次生效
    function debounce(fn, delay) {
      let t; return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), delay); };
    }
    
    // 節流:固定頻率執行
    function throttle(fn, interval) {
      let last = 0; return (...args) => { const now = Date.now(); if (now - last >= interval) { last = now; fn(...args); } };
    }
    

    隨機打亂陣列

    
    function shuffle(arr) {
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
      }
      return arr;
    }
    

    總結

    掌握 JavaScript 型別轉換規則、短路邏輯、字串構建效能、DOM 遍歷模式,能寫出更簡潔、高效、健壯的代碼。現代語法(`??`、`?.`、模板字面量、解構、箭頭函數)已解決大部分歷史痛點,建議全面採用 ES2020+ 標準,並配合 ESLint/TypeScript 靜態分析避免低級錯誤。

    copyright © 萬盛學電腦網 all rights reserved