一、基础的操作
1. 快速数组去重
const arr = [1, 2, 2, 3]
const uniqueArr = [...new Set(arr)]
2. 合并多个对象
const obj1 = { a: 1 }
const obj2 = { b: 2 }
const merged = { ...obj1, ...obj2 }
3. 快速生成连续数字数组
const arr = Array.from({ length: 5 }, (_, i) => i + 1);
二、简化条件判断
1. 替代复杂的 if-else
// 传统写法
if (status === 'success' || status === 'ok' || status === 200) { ... }
// 简化写法
if (['success', 'ok', 200].includes(status)) { ... }
2. 短路运算设置默认值
const name = userInput || '默认名字'
3. 可选链避免报错
// 传统写法
const street = user.address && user.address.street
// 简化写法
const street = user?.address?.street
三、数组操作宝典
1. 快速过滤假值
const arr = [0, '', false, 1, 'hello']
const truthyArr = arr.filter(Boolean)
2. 快速求数组最大值
const max = Math.max(...[1, 5, 3]);
3. 数组转对象
const arr = [['name', 'John'], ['age', 30]]
const obj = Object.fromEntries(arr)
四、字符串处理技巧
1. 模板字符串拼接
const name = 'John';
console.log(`你好,${name}!`);
2. 首字母大写
const capitalize = str => str[0].toUpperCase() + str.slice(1);
console.log(capitalize('hello'));
3. URL参数解析
const params = new URLSearchParams('?name=John&age=30');
console.log(params.get('name'));
五、对象操作基本功
1. 动态属性名
const key = 'age'
const obj = { [key]: 25 }
2. 对象遍历优化
const obj = { a:1, b:2 };
Object.entries(obj).forEach(([key, val]) => {
console.log(key, val); // a 1 → b 2
});
3. 删除对象属性
const obj = { a:1, b:2 };
const { a, ...newObj } = obj; // newObj = {b:2}
六、实用函数技巧
1. 函数参数默认值
function greet(name = '陌生人') {
console.log(`你好,${name}!`);
}
2. 箭头函数简化
arr.map(function(item) { return item * 2; });
arr.map(item => item * 2);
3. 立即执行函数
(() => {
console.log('这个函数会立即执行!');
})();
七、调试小技巧
1. console.table 展示对象数组
const users = [{name:'John', age:25}, {name:'Lucy', age:30}]
console.table(users)
2. 快速深拷贝对象
const obj = { a: 1 }
const copy = JSON.parse(JSON.stringify(obj))
3. 代码执行时间测量
console.time('test');
console.timeEnd('test');
八、现代循环优化
1. for...of 替代传统 for
const arr = [1, 2, 3];
for (const num of arr) {
console.log(num);
}
2. 用 some 提前终止循环
const hasNegative = [1, -2, 3].some(num => num < 0);
3. 用 find 查找元素
const users = [{id:1}, {id:2}]
const user = users.find(u => u.id === 2)