在我的项目中有一个单色屏幕,您可以写入和清除。在类里面,我有这两行代码用于清除屏幕。第一个将当前像素值从屏幕推送到堆栈上,以便稍后可以撤消清屏。第二行清除屏幕。问题是撤消堆栈正在获取对 this.pixels 的引用,而不是获取它当时的值。
this.pushUndo(this.pixels); //this.pixels is an array of ints
this.updateScreen(new Array(64*32)); //this.pixels changes at the end of this line but the undo stack shouldn't change its value
最佳答案
您可以使用slice创建浅副本:
const pixels0 = [0, 1, 2, 3, 4, 5];
const pixels1 = pixels0.slice(0);
// modify only index 0 of copy.
pixels1[0] = 1;
console.log(pixels0);
// expected output: Array [0, 1, 2, 3, 4, 5]
console.log(pixels1);
// expected output: Array [1, 1, 2, 3, 4, 5]
如果您需要深层副本,可以查看What is the most efficient way to deep clone an object in JavaScript?
关于javascript - 如何防止 javascript 在传递对象的子对象时通过引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54138791/