gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:22:50 26 4
gpt4 key购买 nike

我在使用 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;
}
}

当您请求组件代码时。 setValue 方法是通过 .html 按钮点击调用的,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);

}
}

最佳答案

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

import { cloneDeep } from 'lodash';

...

export class ... implements OnInit {

...


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

关于javascript - 对象数组 - 所有对象都等于最后一个 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46494890/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com