【问题标题】:Array referencing in constructor affected by push受推送影响的构造函数中的数组引用
【发布时间】:2022-01-04 22:23:46
【问题描述】:

我不明白为什么推送到数组会影响结果,而更改数组项不会。

如何编写,以便restore 方法返回初始数组?

class Snapshot {
    constructor(array) {
        this.array = [...array];
    }

    restore() {
        return this.array;
    }
}

var array = [1, 2];
var snap = new Snapshot(array);

array[0] = 3;
array = snap.restore();
console.log(array.join()); // Logs "1,2"

array.push(4);
array = snap.restore();
console.log(array.join()); //It should log "1,2", but logs "1,2,4"

【问题讨论】:

  • 你替换了数组....`return this.array;`不是副本

标签: javascript arrays oop


【解决方案1】:

这一行...

array = snap.restore();

snap.array 的对象引用分配给array,因此它们引用相同的对象值。在这个阶段操作array 也会操作snap.array

如果你想打破引用并防止对类成员的外部操作,你需要这个

restore() {
  return [...this.array]
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多