克隆Javascript/Typescript中的数组 [英] Cloning an array in Javascript/Typescript

查看:107
本文介绍了克隆Javascript/Typescript中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象组成的数组:

I have array of two objects:

genericItems: Item[] = [];
backupData: Item[] = [];

我正在用genericItems数据填充HTML表.该表是可修改的.有一个重置按钮可以撤消使用backUpData完成的所有更改.此数组由服务填充:

I am populating my HTML table with genericItemsdata. The table is modifiable. There is a reset button to undo all changes done with backUpData. This array is populated by a service:

getGenericItems(selected: Item) {
this.itemService.getGenericItems(selected).subscribe(
  result => {
     this.genericItems = result;
  });
     this.backupData = this.genericItems.slice();
  }

我的想法是,用户更改将反映在第一个阵列中,而第二个阵列可以用作重置操作的备份.我在这里面临的问题是用户修改表时(genericItems[])第二个数组backupData也被修改了.

My idea was that, the user changes will get reflected in first array and second array can be used as backup for reset operation. The issue I am facing here is when the user modifies the table (genericItems[]) the second array backupData also gets modified.

这是怎么回事,如何预防呢?

How is this happening and how to prevent this?

推荐答案

尝试一下:

克隆对象:

const myClonedObject = Object.assign({}, myObject);

克隆数组:

选项1-如果您具有原始类型的数组:

Option 1 - if you have an array of primitive types:

const myClonedArray  = Object.assign([], myArray);

选项2-如果您有对象数组:(感谢@mumblesNZ)

Option 2 - if you have an array of objects: (thanks @mumblesNZ)

const myArray= [{ a: 'a', b: 'b' }, { a: 'c', b: 'd' }]; 
const myClonedArray = []; 
myArray.forEach(val => myClonedArray.push(Object.assign({}, val)));

这篇关于克隆Javascript/Typescript中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆