false, 0, -0, 0n, '', null, undefined, NaN
其餘皆為 Truthy(包括 `'0'`、`[]`、`{}`、`new Date()`、`function(){}`)。
| 表達式 | 結果 | 原因 |
|---|---|---|
| Boolean('0') | true | 非空字串 |
| '0' == true | false | '0'→1, true→1, 但 '0'==true 為 false(類型轉換規則) |
| 0 == [] | true | []→''→0 |
| [] == false | true | []→''→0, false→0 |
| {} == false | false | {}→'[object Object]'→NaN ≠ 0 |
// 替代 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();
const config = {
timeout: userConfig.timeout ?? 5000,
retries: userConfig.retries ?? 3
};
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('')}
`;
| 方法 | 耗時 |
|---|---|
| 字串 += 迴圈 | ~45ms |
| 陣列 push + join | ~3ms |
| 陣列直接賦值 + join | ~2ms |
| 模板字面量 map + join | ~4ms |
// ❌ 慢:每次迴圈存取 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 => ...);
for (let child = parent.firstChild; child; child = child.nextSibling) {
if (child.nodeType === 1) { // Element 節點
doSomething(child);
}
}
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 靜態分析避免低級錯誤。