【问题标题】:How do I prevent javascript from passing by reference when passing in an object's child传递对象的子对象时如何防止javascript通过引用传递
【发布时间】:2019-06-05 22:04:02
【问题描述】:

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

【问题讨论】:

  • 你可以尝试克隆对象

标签: javascript pass-by-reference pass-by-value


【解决方案1】:

您可以使用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?

【讨论】:

    【解决方案2】:

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

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

    您能否在您的问题中说明updateScreen 方法的内容?

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 2012-06-23
      • 2011-05-14
      • 2017-09-11
      • 2013-11-24
      • 2015-09-19
      • 1970-01-01
      • 2019-03-02
      相关资源
      最近更新 更多