对象展开运算符只复制第一层属性。嵌套对象仍可能是同一个引用,因此给副本的嵌套字段赋值,也会影响原对象。

先确认嵌套字段是不是同一个对象
在浏览器控制台运行。
const source = { profile: { city: "杭州" } };
const shallow = { ...source };
console.log(source === shallow);
console.log(source.profile === shallow.profile);
shallow.profile.city = "苏州";
console.log(source.profile.city);
预期输出 false、true 和苏州。
立即学习“Java免费学习笔记(深入)”;
只更新一条路径时复制那一层
保存其它字段,单独展开需要修改的嵌套对象。
const updated = {
...source,
profile: { ...source.profile, city: "南京" },
};
console.log(source.profile.city, updated.profile.city);预期输出苏州和南京。其它未复制的嵌套层依然可能共享引用。
需要独立数据副本时使用结构化克隆
在支持 structuredClone 的运行环境中试下面的例子。
const independent = structuredClone(source); independent.profile.city = "合肥"; console.assert(source.profile.city === "苏州"); console.assert(independent.profile.city === "合肥");
结构化克隆支持多种数据类型,但函数等值不能这样复制。先按对象类型选择复制方式。


















