别再无脑用 ...
合并对象了,这个新 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()
- 性能敏感的简单数据 → 用
...