对象数组 - 所有对象都等于最后一个javascript

时间:2017-09-29 18:25:35

标签: javascript arrays angular typescript

我遇到了TypeScript对象的问题,并将所有这些对象推入数组并稍后检索它们。

我有一个history对象和pushHistory()方法。我还有一个History对象。它看起来像:

  public history: History[];

  pushHistory(cell, support, pad, empty, time){
    let historyObject = new History(cell, support, pad, empty, time);
    this.history.push(historyObject);    
  }

当我想要检索任何历史值时,例如history[X].data.cell[0][0].value它始终等于最后一个值。通常看起来所有History实例都是同一个实例,所以在我的history数组中它只有一个对象,总是引用最后一个版本。

我的历史对象看起来像:

export class History {
  public cells: Cell[][];
  public support: Support[];
  public pad: Pad[];
  public empty: number;
  public lastTime: ITimer;

  constructor(cells: Cell[][], support: Support[], pad: Pad[], empty: number, lastTime: ITimer) {
    this.cells = cells;
    this.support = support;
    this.pad = pad;
    this.empty = empty;
    this.lastTime = lastTime;
  }
}

当您要求Component代码时。从{html按钮单击调用setValue方法,this.cells来自Android对象(来自Android应用程序)。

export class Componenet implements OnInit {
  @ViewChild(TimerComponent) timer: TimerComponent;

  cells: Cells[][];
  support: Support[];
  pad: Pad[];
  empty: number;
  time: ITimer;
  enumMode: enum;
  enumAction: enum;
  testValue: boolean;

  constructor(private route: ActivatedRoute, private history: HisotryService, private soundService: AudioPlayerService) {
    this.enumMode = Mode;
    this.enumAction = Action;
    this.testValue = false;
  }

  ngOnInit() {
    this.empty = 10;

    if (typeof Android != 'undefined') {
      this.cells = Android.generate();
}


    this.cells = [];
    this.pad = [];
    this.support= [];

    this.history.retriveHistoryObject(JSON.parse(localStorage.getItem('last')));
    const historyObject = this.history.getLastHistoryObject();

    this.cells = historyObject.cells;
    this.support = historyObject.support;
    this.pad = historyObject.pad;

    this.empty = historyObject.emptyCells;

    this.timerStart = historyObject.lastTime;

    setTimeout(() => {
      this.timer.startTimer();
    }, 1000);

  }


  public setValue(number, usage) {
    this.soundService.playClick();

    // CODE that maek operation on this.cells, this.pad, this.empty and so on

    this.history.pushHistory(this.cells, null, this.pad, this.empty, time);

  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用lodash' cloneDeep。它创建一个新的对象实例,而不是引用同一个对象。

import { cloneDeep } from 'lodash';

...

export class ... implements OnInit {

  ...


  public setValue() {
    ...
    const historyCopy = cloneDeep(historyObject);
    this.history.push(historyCopy);
  }
}