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

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

别再无脑用 ... 合并对象了,这个新 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 编程技巧 性能优化

推荐文章

js迭代器
2024-11-19 07:49:47 +0800 CST
你可能不知道的 18 个前端技巧
2025-06-12 13:15:26 +0800 CST
js一键生成随机颜色:randomColor
2024-11-18 10:13:44 +0800 CST
deepcopy一个Go语言的深拷贝工具库
2024-11-18 18:17:40 +0800 CST
平面设计常用尺寸
2024-11-19 02:20:22 +0800 CST
百度开源压测工具 dperf
2024-11-18 16:50:58 +0800 CST
详解 Nginx 的 `sub_filter` 指令
2024-11-19 02:09:49 +0800 CST
WebSQL数据库:HTML5的非标准伴侣
2024-11-18 22:44:20 +0800 CST
跟着 IP 地址,我能找到你家不?
2024-11-18 12:12:54 +0800 CST
浅谈CSRF攻击
2024-11-18 09:45:14 +0800 CST
使用 Go Embed
2024-11-19 02:54:20 +0800 CST
Elasticsearch 文档操作
2024-11-18 12:36:01 +0800 CST
回到上次阅读位置技术实践
2025-04-19 09:47:31 +0800 CST
PHP来做一个短网址(短链接)服务
2024-11-17 22:18:37 +0800 CST
程序员茄子在线接单