我对typescript中的spread运算符感到困惑
当我使用。spread运算符制作object1的副本时。
var object2 = { ...object1, };
我得到一个新的object2,其中包含所有object1项的深层副本,即使object1包含其他对象。
但是,如果object1中有一个数组,则执行浅拷贝。在这种情况下,它似乎维持object1和object2中的数组值之间的关系。
有没有办法使用扩展运算符深度复制数组?
答案 0 :(得分:3)
包含所有object1项目的深层副本的新object2
没有。传播始终是一个浅薄的副本。
let orig = { arr: [1,2,3] }
let copy = {...orig}
copy.arr.push(4)
console.log(orig.arr) // 1 2 3 4
答案 1 :(得分:1)
Spread运算符仅复制对原始数组元素的引用。数组元素指向相同的内存位置。
对于深层复制,我使用lodash中的cloneDeep。
答案 2 :(得分:0)
这不直接回答问题,但我想告诉你我是怎么做的。在打字稿中,我通常为我的对象创建类,并使用构造函数来深度复制相同类型的对象。然后,您可以使用两个构造函数直接传递相同类型的对象或属性。
export class MyObject {
myAttribute:string;
otherAttributes:Array<string>;
constructor();
constructor(myAttributeOrObj?:MyObject|string);
constructor(myAttributeOrObj?:any, otherAttributes:Array<string>){
if(myAttributeOrObj && myAttributeOrObj.myAttribute){
this.myAttribute = myAttributeOrObj.myAttribute;
this.createOtherAttributes(myAttributeOrObj.otherAttributes);
}else{
this.myAttribute=myAttributeOrObj;
this.createOtherAttributes(otherAttributes);
}
}
createOtherAttributes(arr){
this.otherAttributes = [];
for(var i = 0; i< arr.length; i++){
this.otherAttributes.push(arr[i]);
}
}
}
与使用现有库相比,此方法可能会产生开销,但使用此方法,您可以完全控制对象,类型,并且知道您已经创建了深层副本而不是浅层副本。
有关构造函数重载的更多信息,请参阅此问题Constructor overload in TypeScript
答案 3 :(得分:0)
如果您需要深层复制,该怎么做:
var object2 = JSON.parse(JSON.stringify(object1);