You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何复制数组而不产生引用关联?

数组复制后修改原数组导致副本同步变化的问题及解决

问题场景

我想要复制一个数组,但修改原数组的元素时,副本数组的值也会跟着变化。

相关代码实现

组件初始化方法

ngOnInit() {
     this.service.searchTickets().subscribe((resp) => {
  this.dataSource.data = resp.entities;
  this.records = [...this.dataSource.data];
  })
}

滑动开关点击事件处理函数

点击滑动开关时调用以下函数,修改数组元素的属性:

displayValue(value: TicketsList) {
let index;
index = Number(value.key);

this.dataSource.data[value.key!].status = !this.dataSource.data[value.key!].status;
this.dataSource.data[index].supervisor = 'John Woor';
}

HTML模板代码

<mat-slide-toggle
      (click)="displayValue(element)"
      [checked]="element.status"
    ></mat-slide-toggle>

解决方法

最终通过深拷贝方式解决问题,代码如下:

this.records = JSON.parse(JSON.stringify(this.dataSource.data));

内容的提问来源于stack exchange,提问作者domekker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:48:57