简体   繁体   English

如何确保链接两个单独的javascript对象的属性

[英]How to ensure properties of two separate javascript objects are linked

I have 2 objects inside an anuglar service that I want to assign a property called nodes that points to the same array. 我在auglar服务中有2个对象,我想分配一个称为nodes的属性,该属性指向同一数组。 Is this the correct way to do it? 这是正确的方法吗? I am not seeing that the when I make changes to the nodes on 1 object the other is changing 我没有看到当我对一个对象上的节点进行更改时,另一个正在更改

objectOne.nodes = [o1, o2, o3];
objectTwo.nodes = [];
angular.forEach(objectOne.nodes, function(n){
    objectTwo.nodes.push(n); // based on some logic not all n assigned to the objectTwo, some might go to objectThree.
})

Now if I make a change to objectTwo.nodes[i] , I expect this to apply for objectOne.nodes[j] where i and j are the index for the same node in the 2 different objects (since ordering might not match),but I am not seeing this. 现在,如果我对objectTwo.nodes[i]进行了更改,我希望这适用于objectOne.nodes[j] ,其中i和j是2个不同对象中同一节点的索引(因为顺序可能不匹配),但是我没看到 Am i doing something wrong when I push the nodes into objectTwo ? 将节点推入objectTwo时,我objectTwo什么了吗?

PS: I am making the change to objectTwo node on the DOM and both objectOne and ObjectTwo are in mem variables on my service. PS:我正在对DOM上的objectTwo节点进行更改,而objectOne和ObjectTwo都在我的服务的mem变量中。

If you push the same reference of the object, the new array should affect the source as well. 如果您按相同的对象引用,则新数组也将影响源。

 var objectOne = {}, objectTwo = {}, objectThree = {}; objectOne.nodes = [{ id: 1, name: 'o1' }, { id: 2, name: 'o2' }, { id: 3, name: 'o3' }]; objectTwo.nodes = []; objectThree.nodes = []; objectOne.nodes.forEach(function (o) { o.id % 2 ? objectTwo.nodes.push(o) : objectThree.nodes.push(o); }); objectTwo.nodes[1].name += '+'; console.log(objectOne); console.log(objectTwo); console.log(objectThree); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

A little help : 一点帮助 :

 var div = document.createElement("div"); var a = {}, b = {}; a.nodes = b.nodes = []; a.nodes.push(div); div.style.color = "blue"; console.log(a.nodes[0].style.color); console.log(b.nodes[0].style.color); div.style.color = "red"; console.log(a.nodes[0].style.color); console.log(b.nodes[0].style.color); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM