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
相关产品推荐
相关产品推荐

