为什么在我修改克隆的 obj 时 obj 会发生变化(使用 {...})?
Why the obj is being mutated when I am modifying the cloned obj ( using {...})?
让我们拿一个对象d。
var d = {
"e":{
"f": 3
}
}
现在使用{...}将d
复制到t
并分配新道具。
var t = {...d}
t.e._f = 4
为什么对象 d 被突变为
{
"e": Object {
"_f": 4,
"f": 3
}
}
你正在做浅拷贝。 {...d}
等同于 Object.assign({}, d)
,后者又将属性复制到 one 层深。 Docs.
For deep cloning, we need to use other alternatives because
Object.assign() copies property values. If the source value is a
reference to an object, it only copies that reference value.
所以 t.e === d.e
引用同一个对象。
让我们拿一个对象d。
var d = {
"e":{
"f": 3
}
}
现在使用{...}将d
复制到t
并分配新道具。
var t = {...d}
t.e._f = 4
为什么对象 d 被突变为
{
"e": Object {
"_f": 4,
"f": 3
}
}
你正在做浅拷贝。 {...d}
等同于 Object.assign({}, d)
,后者又将属性复制到 one 层深。 Docs.
For deep cloning, we need to use other alternatives because Object.assign() copies property values. If the source value is a reference to an object, it only copies that reference value.
所以 t.e === d.e
引用同一个对象。