我如何让两个对象访问同一数组[重复]

问题描述 投票:0回答:3
Class A实例化为一个对象,该对象具有一个名为this.people的数组,该数组中填充有大量数据。 A类实例化B类的对象,然后将this.people传递给它的构造函数。如果对象B更新了数组,则对象A更新它时,它将覆盖对象B的更改。如何解决此问题?
javascript es6-class
3个回答
0
投票
之所以会这样,是因为您将A的people数组的引用传递给B的构造函数。您想对A的people数组进行“浅拷贝”或“深拷贝”,因为您希望B的people数组内容不同。

使用“浅表复制”,您将数组中的所有原始值都复制到新值中,但是如果您在数组中具有复合值(数组或对象),则仅复制对它们的引用,因此任何对复合值所做的更改将同时反映在A和B中。使用“深度复制”,原始值和复合值(而不仅仅是它们的引用)都将被复制到内存中的新位置。

如果people数组中没有对象和数组,则可以使用Array.from(a.people)进行浅表复制。否则,您可以使用JSON.parse(JSON.stringify(a.people))

进行深度复制

摘要:

class B { constructor(_people) { // shallow copy: this.people = Array.from(_people); // deep copy: //this.people = JSON.parse(JSON.stringify(_people)); } } class A { constructor() { this.people = []; } func() { this.objB = new B(this.people); //do something } } // Usage Example let objA = new A(); objA.people.push("A"); objA.func(); objA.objB.people.push("B"); console.log(objA.people.toString()); console.log(objA.objB.people.toString());
一些有用的链接:https://medium.com/@gamshan001/javascript-deep-copy-for-array-and-object-97e3d4bc401a

https://dev.to/samanthaming/how-to-deep-clone-an-array-in-javascript-3cig


-1
投票
给每个班级自己的people版本

class A{ constructor(){ this.people = ["bob","jane","john"] this.objB = new B(this.people) } } class B{ constructor(people){ this.people = people } } let objA = new A() objA.objB.people.push("a") objA.people.push("b") console.log(objA.people, objA.objB.people)

-1
投票
destructuring按值传递数组。

class Family { constructor(people) { this.people = people; } } let members = ["mom", "dad"]; let smiths = new Family(members); let joneses = new Family(smiths.people); // pass by reference joneses.people.push("Billy"); console.log(smiths.people); // changes to ["mom","dad","Billy"] let wilsons = new Family([...smiths.people]); // pass by value wilsons.people.push("Suzy"); console.log(smiths.people); // remains ["mom","dad","Billy"]
© www.soinside.com 2019 - 2024. All rights reserved.