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

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

问题描述

我有两个对象的数组:

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 如果您有原始类型的数组:

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

  • 选项 2 - 如果您有一组对象:
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天全站免登陆