JavaScript: assignment to an object within an array changes the value of all objects in the array -


i have object have array hold children of object, children instances of same object (i need tree structure object node of tree)

var bugobject = function(kflag){   this._kflag = kflag;    this._children = [] }  bugobject.prototype.getkflag = function(){   return this._kflag;  };    bugobject.prototype.setchildrenfromdata = function(data){   var = 0;  var kflag = {flagtype : 'someflag', flagvalue : -1};  kddflag.flagtype = data.flagtype;   var len = data.flagvalues.length;   for( = 0 ; < len ; i++){         kflag.flagvalue = data.flagvalues[i];         this._children.push(             new bugobject(kflag)         );                   //this print children          for(j = 0; j<=i; j++){             console.log('child : ' + j + ' test :' + i);              console.log(this._children[i].getkflag());         }         console.log('--------------------');  }  };  

the idea create children of object based on data using setchildrenfromdata method here how doing this:

function main(){  console.log('main called');  var data = {"flagtype":"someflag","flagvalues":[0,0,0,0,0,0,0,0,1,0,0]};   var rootnode = new bugobject(null);  rootnode.setchildrenfromdata(data);   }  main();  

the problem instead of getting 11 objects each of them have 1 of these flags [0,0,0,0,0,0,0,0,0,0,1] 11 objects of them have flag 1, (the last one)!

could please see wrong!

thanks

the problem this:

for( = 0 ; < len ; i++){         kddflag.flagvalue = data.flagvalues[i];         this._children.push(             new bugobject(kddflag)         ); 

you're creating 11 bugobject. of them have this._kddflag pointing same kddflag object, @ end of loop kddflag.flagvalue 1. fix this, move code loop. this:

for( = 0 ; < len ; i++){            var kddflag = {flagtype : 'outlier', flagvalue : -1};             kddflag.flagtype = data.flagtype;             kddflag.flagvalue = data.flagvalues[i];             this._children.push(                new bugobject(kddflag)             ); 

Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -