在另一个对象javascript中引用对象

时间:2015-03-04 19:34:24

标签: javascript object reference pass-by-reference

所以我有两组不同的对象:

var house = {};
house["01"] = {hID: "01", neighbh: "00001", name: "house 1"};
house["02"] = {hID: "02", neighbh: "00001", name: "house 2"};
house["03"] = {hID: "03", neighbh: "00002", name: "house 3"};
house["04"] = {hID: "04", neighbh: "00003", name: "house 4"};

var neighborhood = {};
neighborhood["00001"] = {id: "00001", name: "first neighborhood", houses: {} };
neighborhood["00002"] = {id: "00002", name: "second neighborhood", houses: {} };
neighborhood["00003"] = {id: "00003", name: "third neighborhood", houses: {} };

我希望能够在附近的房屋{}内引用房屋对象。但过滤它们到各自的邻居。即房子[" 01"]应该在附近[" 00001"](那些邻居id匹配房子邻居的那些)。这样我可以将所有房屋放在一个不同的对象中,但仍然可以通过邻居对象对它们进行更改。希望我已经设法让自己清楚了。

任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

Javascript中的对象通过引用传递和存储。所以,假设你拥有所有房屋的主阵列:

var houses = [
    {hID: "01", neighbh: "00001", name: "house 1"},
    {hID: "02", neighbh: "00001", name: "house 2"}
];

然后,你有一系列邻居对象,每个对象都有一些关于邻居的识别信息,然后是该社区的房屋清单:

var neighborhoods = [
    {id: "00001", name: "first neighborhood", houses: [houses[0], houses[1]]} 
];

在这样的结构中,每个房屋对象只有一个副本。您可以通过任何参考修改它。所以,你可以通过master houses数组修改它。或者,您可以通过附近的房屋阵列修改它。每个都指向完全相同的房屋对象。因此,当您在一个地方修改它时,您正在修改实际的房屋对象,并且每个对该特定房屋对象有引用的人都会看到这些修改。


所以,在你所假设的结构中(它使用对象作为容器而不是我用来容纳多个项目的数组)。我认为你可以这样填写,并完成你要求的:

var house = {};
house["01"] = {hID: "01", neighbh: "00001", name: "house 1"};
house["02"] = {hID: "02", neighbh: "00001", name: "house 2"};
house["03"] = {hID: "03", neighbh: "00002", name: "house 3"};
house["04"] = {hID: "04", neighbh: "00003", name: "house 4"};

var neighborhood = {};
neighborhood["00001"] = {id: "00001", name: "first neighborhood", houses: [house["01"], house["02"]]};
neighborhood["00002"] = {id: "00002", name: "second neighborhood", houses: [house["03"]] };
neighborhood["00003"] = {id: "00003", name: "third neighborhood", houses: [house["04"]] };

仅供参考,看起来社区中的房屋清单应该是一个数组,而不是一个对象。