JS小技巧

48 阅读1分钟

一、基础的操作

1. 快速数组去重

const arr = [1, 2, 2, 3];
const uniqueArr = [...new Set(arr)]; // [1, 2, 3]

2. 合并多个对象

const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = { ...obj1, ...obj2 }; // { a:1, b:2 }

3. 快速生成连续数字数组

const arr = Array.from({ length: 5 }, (_, i) => i + 1); // [1,2,3,4,5]

二、简化条件判断

1. 替代复杂的 if-else

// 传统写法
if (status === 'success' || status === 'ok' || status === 200) { ... }

// 简化写法
if (['success', 'ok', 200].includes(status)) { ... }

2. 短路运算设置默认值

const name = userInput || '默认名字'; // 如果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); // [1, 'hello']

2. 快速求数组最大值

const max = Math.max(...[1, 5, 3]); // 5

3. 数组转对象

const arr = [['name', 'John'], ['age', 30]];
const obj = Object.fromEntries(arr); // {name: 'John', age:30}

四、字符串处理技巧

1. 模板字符串拼接

const name = 'John';
console.log(`你好,${name}!`); // 你好,John!

2. 首字母大写

const capitalize = str => str[0].toUpperCase() + str.slice(1);
console.log(capitalize('hello')); // Hello

3. URL参数解析

const params = new URLSearchParams('?name=John&age=30');
console.log(params.get('name')); // John

五、对象操作基本功

1. 动态属性名

const key = 'age';
const obj = { [key]: 25 }; // {age:25}

2. 对象遍历优化

const obj = { a:1, b:2 };
Object.entries(obj).forEach(([key, val]) => {
  console.log(key, val); // a 1b 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); // 1 → 2 → 3
}

2. 用 some 提前终止循环

const hasNegative = [1, -2, 3].some(num => num < 0); // true

3. 用 find 查找元素

const users = [{id:1}, {id:2}];
const user = users.find(u => u.id === 2); // {id:2}