Object.assign无法正确复制 [英] Object.assign does not copy correctly
问题描述
我正在使用VueJS.
I'm working with VueJS.
我有一个接收对象作为参数的方法.
I have a Method that receives a Object as argument.
然后我用 Object.assign()
克隆此对象.
Component.vue
export default {
// ...
methods: {
// ...
activateEditMode (item) {
this.editItemIndex = this.travelItinerary.indexOf(item)
this.editItem = Object.assign({}, item)
// ...
}
}
}
位于 this.roteiroCompleto [0]
处的原始对象:
但是当我编辑克隆对象 this.itemEditado
:
But when I edit the clone Object this.itemEditado
:
原始对象 this.roteiroCompleto [0]
也发生了变化.
the original Object this.roteiroCompleto[0]
changes too.
我试图复制每个键和值,仅复制具有 .slice()
, .map(a => a)
的数组,但没有任何效果.这两个对象保持绑定.
I tried to copy each key and value, copy only the Array with .slice()
, .map(a=>a)
, and nothing works. The two objects keep binding.
当我 console.log(this.itemEditado)
时,我得到了:
奇怪的是,在另一个Vue组件中,我使用了相同的策略,并且有效.
The strange thing is, in another Vue Component, I use the same strategy, and it works.
推荐答案
Object.assign
仅对键和值进行浅表复制,这意味着对象中的一个值是另一个对象或数组,则它与原始对象上的引用相同.
Object.assign
only does a shallow copy of the keys and values, meaning if one of the values in the object is another object or an array, then it is the same reference as was on the original object.
var x = { a: 10, b: { c: 100 } };
var y = Object.assign({}, x);
y.a = 20;
console.log( x.a, y.a ); // prints 10 20
y.b.c = 200;
console.log( x.b.c, y.b.c ) // prints 200 200
要深层复制对象,可以在lodash中使用类似 cloneDeep 函数的方法,也可以使用更丑陋的方法使用带有 JSON.parse(JSON.stringify(obj))
的内置函数的方法.
To deep copy an object, you can using something like the cloneDeep function in lodash or take an uglier approach using built in functions with JSON.parse( JSON.stringify( obj ) )
.
请注意,第二个选项仅适用于JSON支持的原始类型.
Note that the second option will only work with primitive types that are supported by JSON.
这篇关于Object.assign无法正确复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!