如何在打字稿中深度克隆数组

How to deep clone array in typescript

我正在处理日期和时间。我有从上午 9 点到下午 5 点的日历和默认时间段。 我需要通过计算来自 selectedDatesTiming 参数的时间,在 timeList 参数中将 checked 属性 标记为 true。 但它也会在 staticTime 变量中更新相同的时间。 我无法理解这种行为。因为我通过与 selectedDatesTiming 参数进行比较来仅更新 timeList 参数。 请给出一些解决方案。

 import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

 timeList: any = [
    { id: 1, checked: false, time: '09:00 am' },
    { id: 2, checked: false, time: '10:00 am' },
    { id: 3, checked: false, time: '11:00 am' },
    { id: 4, checked: false, time: '12:00 am' },
    { id: 5, checked: false, time: '01:00 pm' },
    { id: 6, checked: false, time: '02:00 pm' },
    { id: 7, checked: false, time: '03:00 pm' },
    { id: 8, checked: false, time: '04:00 pm' },
    { id: 9, checked: false, time: '05:00 pm' },
  ];

   staticTime: any = [
    { id: 1, checked: false, time: '09:00 am' },
    { id: 2, checked: false, time: '10:00 am' },
    { id: 3, checked: false, time: '11:00 am' },
    { id: 4, checked: false, time: '12:00 am' },
    { id: 5, checked: false, time: '01:00 pm' },
    { id: 6, checked: false, time: '02:00 pm' },
    { id: 7, checked: false, time: '03:00 pm' },
    { id: 8, checked: false, time: '04:00 pm' },
    { id: 9, checked: false, time: '05:00 pm' },
  ];

  selectedDatesTiming: any = [
    {time:'09:00 am'},
    {time:'10:00 am'}
  ]

ngOnInit(){
  this.show();
}

show(){

   this.timeList = null;

   setTimeout(() => {

        this.timeList = this.staticTime;

        for (let index = 0; index < this.timeList.length; index++) {
          for (let index1 = 0; index1 < this.selectedDatesTiming.length; index1++) {
            if (this.selectedDatesTiming[index1].time === this.timeList[index].time) {
              this.timeList[index].checked = true;
            }
          }
        }

        console.log(this.staticTime);
        console.log(this.timeList);
      }, 500);
}

}

https://stackblitz.com/edit/settimeout-ay4l3b?file=app%2Fapp.component.ts

试试这个..

从您的代码中删除这一行。

this.timeList = this.staticTime;

并添加这一行..

this.timeList = JSON.parse(JSON.stringify(this.staticTime));