编程 别再无脑用 `...` 合并对象了,这个新 API 更快更安全

2025-08-15 12:09:19 +0800 CST views 953

别再无脑用 ... 合并对象了,这个新 API 更快更安全

在 JavaScript 中,用扩展运算符(...)合并对象几乎成了肌肉记忆:

const defaults = { theme: 'dark', version: '1.0' };
const userConfig = { theme: 'light', showTips: true };

const finalConfig = { ...defaults, ...userConfig };
// { theme: 'light', version: '1.0', showTips: true }

简洁、直观,但在某些场景下,它不仅可能带来性能问题,还可能埋下数据污染的隐患。


1. ...Object.assign() 的共同问题:浅拷贝

两者都是浅拷贝,当属性值是对象或数组时,只会复制引用。

const source = {
  profile: { age: 25, hobbies: ['coding'] }
};
const merged = { ...source };
merged.profile.age = 30;

console.log(source.profile.age); // ❌ 30(原对象被污染)

在复杂项目中,这种副作用可能导致难以追踪的 Bug。


2. 新方案:structuredClone()

Web 平台提供了原生 结构化克隆 API,可以深拷贝对象,彻底隔离引用。

const source = {
  profile: { age: 25, hobbies: ['coding', 'reading'] }
};

// 深拷贝 + 合并
const safeMerged = { ...structuredClone(source), user: 'Bob' };
safeMerged.profile.age = 30;

console.log(source.profile.age); // ✅ 25(安全)

3. 什么时候用?

  • 简单对象(无嵌套引用):...Object.assign() 更快。
  • 复杂对象(嵌套对象/数组):structuredClone() 保证安全。

💡 建议

  • 配置合并Redux state深层数据更新 → 用 structuredClone()
  • 性能敏感的简单数据 → 用 ...
复制全文 生成海报 JavaScript 编程技巧 性能优化

推荐文章

用 Rust 构建一个 WebSocket 服务器
2024-11-19 10:08:22 +0800 CST
Vue3中的组件通信方式有哪些?
2024-11-17 04:17:57 +0800 CST
Golang 随机公平库 satmihir/fair
2024-11-19 03:28:37 +0800 CST
纯CSS实现3D云动画效果
2024-11-18 18:48:05 +0800 CST
thinkphp swoole websocket 结合的demo
2024-11-18 10:18:17 +0800 CST
一个有趣的进度条
2024-11-19 09:56:04 +0800 CST
Vue3中的虚拟滚动有哪些改进?
2024-11-18 23:58:18 +0800 CST
使用xshell上传和下载文件
2024-11-18 12:55:11 +0800 CST
在 Vue 3 中如何创建和使用插件?
2024-11-18 13:42:12 +0800 CST
Vue3中如何处理WebSocket通信?
2024-11-19 09:50:58 +0800 CST
支付宝批量转账
2024-11-18 20:26:17 +0800 CST
Python 获取网络时间和本地时间
2024-11-18 21:53:35 +0800 CST
程序员茄子在线接单