'use strict';` 或模組自動啟用,捕捉隱性錯誤、禁用 `with`、保留字保護。const/let:預設 `const`,需重新賦值才用 `let`,**禁用 `var`** (函數作用域、提升、重複宣告不報錯)。===:避免 `==` 隱性型別轉換 (`[] == false` 為 `true`)。const { a = 1, b = 2 } = opts || {}; 防禦性編程。const arr2 = [...arr1]; const obj2 = { ...obj1 }; 取代 `slice()`/`Object.assign()`。?. 與空值合併 ??:user?.profile?.name ?? '匿名' 替代 `&&` 鏈與 `||` (後者會誤判 `0`、`''`)。Array.isArray():跨 iframe 也準確,`instanceof Array` 失效於多框架。Object.prototype.toString.call(obj) === '[object Object]' 或 `_.isPlainObject()`。const typeOf = x => Object.prototype.toString.call(x).slice(8, -1).toLowerCase();
// typeOf(null) === 'null', typeOf([]) === 'array', typeOf(/re/) === 'regexp'
const x = 1, y = 2; const obj = { x, y };。const obj = { [key]: value };。for (const [k, v] of Object.entries(obj))。const merged = { ...defaults, ...userConfig }; (淺合併,深層需 lodash.merge 或遞迴)。[...new Set(arr)] (保留順序、支援 NaN)。arr.flat(Infinity) (ES2019)。Object.groupBy(items, item => item.category) (ES2024 / Chrome 117+)。Math.max(...arr)、arr.reduce((a,b) => Math.max(a,b), -Infinity) (大陣列避免堆疊溢位)。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]]; }。Array.from({ length: 10 }, (_, i) => i + 1) → [1..10]。this/arguments/super/new.target:適合回呼、不適合物件方法/建構函數。function foo(x = expensive()) {} 每次呼叫無參數都會執行 `expensive()`。...args 取代 arguments:真陣列、支援解構、語意明確。(() => { /* 私有狀態 */ })();。const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);。Promise.all (全成功)、Promise.allSettled (全完成)、Promise.race (最快)、Promise.any (首個成功)。try { const data = await fetch(); } catch (e) { handle(e); } 或封裝 to(promise) => [err, data]。Promise.all(items.map(item => doAsync(item)))。AbortController + fetch(signal) / 手動旗標檢查。Promise.then、queueMicrotask 比 `setTimeout` 早執行,用於狀態同步。document.querySelectorAll 回傳靜態 NodeList:可安全迴圈中修改 DOM,`getElementsByClassName` 回傳即時 HTMLCollection。element.closest(selector):向上尋找最近祖先 (含自己),替代 jQuery `closest`。element.matches(selector):判斷元素是否符合選擇器,事件委派核心:if (e.target.matches('.btn'))。IntersectionObserver 懶載入/曝光埋點:效能遠優於 scroll 事件。ResizeObserver 監測元素尺寸變化:替代 resize 事件、支援內容變化觸發。MutationObserver 監測 DOM 變動:替代 DOMSubtreeModified (已移除)。Clipboard API 非同步讀寫剪貼簿:navigator.clipboard.writeText(str) 需 HTTPS + 使用者手勢。FileReader / `blob.stream()` / `File.arrayBuffer()`:現代檔案讀取流程。requestIdleCallback / Web Worker 分批處理:不阻塞主執行緒。performance.memory (Chrome)。| 原文 # | 原文標題 | 現代對應/補充 |
|---|---|---|
| 1 | 首次賦值用 var | ❌ 棄用,改用 const/let |
| 2 | 用 === | ✅ 保留 |
| 3 | 閉包私有變數 | ✅ 保留,或用 #private fields (ES2022) |
| 4 | 分號結尾 | ✅ Prettier 自動管理 |
| 5 | 建構函數 | → class 語法糖 |
| 6 | typeof/instanceof/constructor 注意 | → Object.prototype.toString / Array.isArray / Symbol.toStringTag |
| 7 | IIFE | ✅ 保留 (模組化前) |
| 8 | 陣列隨機取元素 | ✅ arr[Math.random() * arr.length | 0] |
| 9 | 範圍隨機數 | ✅ Math.random() * (max-min+1) + min | 0 |
| 10 | 0..max 陣列 | → Array.from({length: max+1}, (_,i)=>i) |
| 11 | 隨機字母數字字串 | → crypto.randomUUID() / Array.from(crypto.getRandomValues(new Uint8Array(16))).map(b=>b.toString(16).padStart(2,'0')).join('') |
| 12 | 打亂陣列 | → Fisher-Yates (見上) |
| 13 | String.trim | ✅ 原生 'str'.trim() (ES5+) |
| 14 | 陣列合併 push.apply | → arr1.push(...arr2) / [...arr1, ...arr2] |
| 15 | arguments 轉陣列 | → [...arguments] / Array.from(arguments) |
| 16 | 驗證數字 | → Number.isFinite() + !Number.isNaN() |
| 17 | 驗證陣列 | → Array.isArray() |
| 18 | 陣列最大/最小值 | → Math.max(...arr) / reduce |
| 19 | 清空陣列 length=0 | ✅ 保留 (就地修改) |
| 20 | 不要用 delete 刪陣列項 | ✅ 保留,用 splice/filter |
| 21 | length 截短陣列 | ✅ 保留 |