如何克隆对象数组 TypeScript? [英] How to clone array of objects TypeScript?
问题描述
我尝试过这种方法:
this.plans = [];
this.plansCopy = [...this.plans];
似乎它不起作用,因为返回重复.
Seems it does not work cause returns duplictions.
推荐答案
展开运算符返回数组的各个项目.如果这些已经是对象,那么它会将 references 返回给这些对象.[]
部分正在创建一个新数组.因此你有一个新数组,但它仍然包含相同的对象引用,所以 this.plans[0].oper()
将调用 this.plansCopy[0].oper()
同时.
The spread operator returns the individual items of the array. If these are already objects, then it's returning the references to those objects. It's the []
part that is creating a new array. Thus you have a new array, but it will still contain the same object references, so this.plans[0].oper()
will call this.plansCopy[0].oper()
at the same time as well.
相反,您需要克隆每个单独的对象.有很多不同的方法可以做到这一点(创建数组或单个对象的深层副本).如果您只需要一级克隆,您可以:
Instead you need to clone each individual object. There are a lot of different ways to do this (create deep copy of the array or individual objects). If you only need one level of cloning you can do:
this.plansCopy = this.plans.map(obj => ({...obj}));
这将创建一个新数组,其中每个元素都是每个对象的副本.
This will create a new array where each element is a copy of each object.
这篇关于如何克隆对象数组 TypeScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!