20 个 js 实用技巧,让你代码更简洁高效

1,021 阅读3分钟

1. 解构赋值与重命名

在解构对象时,可以直接重命名变量,避免命名冲突。

const user = { name: 'yun', age: 25 };
const { name: userName, age: userAge } = user;

console.log(userName); // yun
console.log(userAge);  // 25

应用场景:从 API 返回的数据中提取字段时,字段名与现有变量冲突。

2. 快速移除数组中的假值

filter(Boolean) 是清理数组中无效值的利器。

const arr = [0, 'hello', null, 42, false, 'world'];
const filtered = arr.filter(Boolean);

console.log(filtered); // ["hello", 42, "world"]

应用场景:清理用户输入或 API 返回的数组。

3. 数组去重

使用 Set 快速去重。

const arr = [1, 2, 2, 3, 3, 4];
const unique = [...new Set(arr)];

console.log(unique); // [1, 2, 3, 4]

应用场景:处理重复数据时。

4. 按属性对对象数组排序

使用 sort() 方法轻松实现对象数组排序。

const users = [  { name: 'yun', age: 25 },  { name: 'mu', age: 20 }];
users.sort((a, b) => a.age - b.age);

console.log(users);
// [{ name: 'yun', age: 20 }, { name: 'mu', age: 25 }]

应用场景:对用户列表、商品列表等数据排序。

5. 数组扁平化

使用 Array.flat(Infinity) 展平多层嵌套数组。

const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]

应用场景:处理嵌套 JSON 数据或数组。

6. 快速获取数组最后一项

使用 arr.at(-1) 获取数组最后一项。

const arr = [1, 2, 3, 4];
console.log(arr.at(-1)); // 4

应用场景:处理栈或队列时。

7. 生成连续数字数组

使用 Arraykeys() 快速生成连续数字数组。

const numbers = [...Array(5).keys()];
console.log(numbers); // [0, 1, 2, 3, 4]

应用场景:生成索引或序列。

8. 合并对象

使用扩展运算符合并对象。

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

console.log(merged); // { a: 1, b: 2 }

应用场景:合并配置或状态对象。

9. 快速删除对象属性

通过解构赋值删除对象中的某些属性。

const { unwanted, ...rest } = { unwanted: 0, a: 1, b: 2 };
console.log(rest); // { a: 1, b: 2 }

应用场景:清理对象中的无用字段。

10. 首字母大写

快速将字符串首字母大写。

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

应用场景:格式化用户输入或显示内容。

11. 记忆化函数

缓存函数结果,避免重复计算。

const memoize = (fn) => {
  const cache = {};
  return (...args) => {
    const key = JSON.stringify(args);
    if (!cache[key]) {
      cache[key] = fn(...args);
    }
    return cache[key];
  };
};

const slowSquare = (n) => n * n;
const memoizedSquare = memoize(slowSquare);

console.log(memoizedSquare(4)); // 16
console.log(memoizedSquare(4)); // 16 (从缓存中获取)

应用场景:优化计算密集型函数。

12. 防抖函数

限制高频触发的函数调用。

function debounce(fn, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

应用场景:搜索框输入、窗口调整大小事件。

13. 节流函数

控制函数调用频率。

function throttle(fn, delay) {
  let last = 0;
  return function(...args) {
    const now = Date.now();
    if (now - last >= delay) {
      fn.apply(this, args);
      last = now;
    }
  };
}

应用场景:滚动事件、鼠标移动事件。

14. 安全访问嵌套属性

使用可选链操作符安全访问嵌套属性。

const user = { address: { street: 'Main St' } };
console.log(user?.address?.street); // 'Main St'
console.log(user?.contact?.phone); // undefined

应用场景:避免访问未定义属性时报错。

15. 空值合并运算符

为变量提供默认值。

const value = null ?? 'default';
console.log(value); // 'default'

应用场景:处理空值或未定义值。

16. 格式化日期

使用 Intl.DateTimeFormat 格式化日期。

const date = new Date();
const formatted = new Intl.DateTimeFormat('zh-CN', {
  dateStyle: 'full',
}).format(date);

console.log(formatted); // 2024年11月24日星期日

应用场景:国际化项目中显示用户友好的日期格式。

17. 生成随机颜色

快速生成随机颜色。

const randomColor = () => `#${Math.floor(Math.random() * 16777215).toString(16)}`;
console.log(randomColor()); // '#a3e12f'

应用场景:动态生成颜色主题。

18. Promise 超时处理

为异步操作设置超时时间。

const timeout = (promise, ms) => {
  return Promise.race([
    promise,
    new Promise((_, reject) => setTimeout(() => reject('timeout'), ms))
  ]);
};

应用场景:网络请求超时处理。

19. localStorage 封装

封装 localStorage,简化数据存储。

const storage = {
  set: (key, value) => localStorage.setItem(key, JSON.stringify(value)),
  get: (key) => JSON.parse(localStorage.getItem(key)),
};

storage.set('user', { name: 'Yun' });
console.log(storage.get('user')); // { name: 'Yun' }

应用场景:本地存储用户数据。

20. 优雅的 console.log

为日志添加时间戳和样式。

const log = (...args) => console.log(`%c[${new Date().toLocaleTimeString()}]`, 'color: #bada55', ...args);
log('Hello, world!'); // [12:34:56] Hello, world!

应用场景:调试时更清晰地查看日志。