传入对象的子项时,如何防止 javascript 通过引用传递

How do I prevent javascript from passing by reference when passing in an object's child

在我的项目中有一个可以写入和清除的单色屏幕。在 class 中,我有这两行用于清除屏幕的代码。第一个将当前像素值从屏幕推入堆栈,以便稍后可以撤消清除屏幕。第二行清除屏幕。问题是撤消堆栈正在获取对 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?

我通常在需要克隆值时使用 Object.assign。 示例:

const clone = Object.assign([], yourArray);

你能展示一下你问题中 updateScreen 方法的内容吗?