在日常開發中,JavaScript 是我們繞不開的核心語言。無論你是前端開發、全棧工程師,還是剛入門的初學者,掌握一些實用的 JavaScript 技巧,不僅能大幅提升開發效率,還能讓你的代碼更加優雅、簡潔。
下面整理了 50 個常用且高頻的 JavaScript 技巧,涵蓋數組、對象、函數、DOM 操作等多個實戰場景,每個技巧都配有簡潔的示例代碼,拿來就能用,快來查漏補缺吧!
一.基礎技巧
1.使用??代替||處理 null/undefined
const name = null;
console.log(name ?? 'Guest');
2.使用?.
安全訪問嵌套屬性
const user = {};
console.log(user.address?.city);
3.轉換為布爾值
const loggedIn = !!user; // true 或 false
4.數字轉字符串 / 字符串轉數字
String(123);
Number("456");
5.使用typeof
檢查變量類型
二、數組技巧
6.去重數組
const nested = [1, [2, [3]]];
nested.flat(2);
7.查找最大值/最小值
Math.max(...[1, 2, 3]); // 3
Math.min(...[1, 2, 3]); // 1
8.打亂數組順序
const arr = [1, 2, 3];
arr.sort(() => Math.random() - 0.5);
9.生成固定長度數組
Array.from({ length: 5 }, (_, i) => i + 1);
10.數組扁平化
const nested = [1, [2, [3]]];
nested.flat(2);
11.數組分組
const groupBy = (arr, fn) =>
arr.reduce((acc, val) => {
const key = fn(val);
(acc[key] = acc[key] || []).push(val);
return acc;
}, {});
三、對象技巧
12.合并對象
const merged = { ...obj1, ...obj2 };
13.對象鍵值互換
const obj = { a: 1, b: 2 };
const flipped = Object.fromEntries(
Object.entries(obj).map(([k, v]) => [v, k])
);
14.從對象中提取部分屬性
15.動態屬性名
const key = "name";
const user = { [key]: "Tom" };
16.刪除對象中 falsy 值
Object.fromEntries(Object.entries(obj).filter(([k, v]) => v));
四、函數技巧
17.默認參數
function greet(name = 'Guest') {
console.log(`Hello, ${name}`);
}
18.箭頭函數簡寫
const double = x => x * 2;
19.立即執行函數(IIFE)
(() => {
console.log("Executed!");
})();
20.函數緩存(記憶化)
const memo = fn => {
const cache = {};
return x => cache[x] || (cache[x] = fn(x));
};
21.函數節流(throttle)
function throttle(fn, delay) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last > delay) {
last = now;
fn(...args);
}
};
}
22.函數防抖(debounce)
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
五、時間處理技巧
23.獲取當前時間戳
24.格式化時間
new Date().toLocaleString();
25.延遲執行
setTimeout(() => console.log("Hi"), 1000);
26.每秒執行
const interval = setInterval(() => console.log("Tick"), 1000);
clearInterval(interval);
六、字符串操作技巧
27.模板字符串
const msg = `Hello, ${name}`;
28.字符串反轉
"hello".split("").reverse().join(""); // "olleh"
29.字符串重復
"abc".repeat(3); // "abcabcabc"
30.替換所有
"foo foo".replaceAll("foo", "bar"); // "bar bar"
31.檢查字符串開頭/結尾
str.startsWith("Hello");
str.endsWith("!");
七、邏輯與運算技巧
32.三元表達式
const status = isActive ? "active" : "inactive";
33.簡寫 if
isLoggedIn && showDashboard();
34.短路賦值
35.按位取整
36.指數操作
八、工具類技巧
37.深拷貝對象
const deepCopy = JSON.parse(JSON.stringify(obj));
38.獲取對象長度
39.判斷是否為數組
40.隨機字符串
Math.random().toString(36).slice(2);
41.生成唯一 ID
const uuid = () => Date.now().toString(36) + Math.random().toString(36).slice(2);
九、DOM 操作技巧
42.選擇元素
document.querySelector(".btn");
43.添加事件
btn.addEventListener("click", () => alert("Clicked"));
44.創建元素
const el = document.createElement("div");
45.設置 innerHTML
el.innerHTML = "<p>Hello</p>"
46.設置樣式
47.操作類名
el.classList.add("active");
el.classList.remove("hidden");
十、實用判斷技巧
48.判斷空對象
Object.keys(obj).length === 0;
49.判斷為空值(null, undefined, "")
50.判斷是否為數字
該文章在 2025/6/5 15:12:38 編輯過