在 Angular 2 + TypeScript 中深度复制数组 [英] Deep copy an array in Angular 2 + TypeScript
本文介绍了在 Angular 2 + TypeScript 中深度复制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组作为输入.我们称之为content
.
I have an array of objects that is an input. Lets call it content
.
尝试深度复制时,它仍然引用了前一个数组.
When trying to deep copy it, it still has a reference to the previous array.
我需要复制该输入数组,并更改复制部分的一个属性.
I need to duplicate that input array, and change one property of the duplicated part.
这么长时间以来,我尝试了不同的方法,但都没有成功.
So long I've tried different methods that weren't successful.
ES6 方式:
public duplicateArray() {
arr = [...this.content]
arr.map((x) => {x.status = DEFAULT});
return this.content.concat(arr);
}
slice
方式:
public duplicateArray() {
arr = this.content.slice(0);
arr.map((x) => {x.status = DEFAULT});
return this.content.concat(arr);
}
在这两个数组中的所有对象都具有 status: 'Default'
.
In both of them all the objects inside the array have status: 'Default'
.
在 Angular 2 中深度复制数组的最佳方法是什么?
What's the best approach to deep copy the array in Angular 2?
推荐答案
检查这个:
let cloned = source.map(x => Object.assign({}, x));
这篇关于在 Angular 2 + TypeScript 中深度复制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文