在日常开发中,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 编辑过