Reputation: 609
I've a strange problem while assigning the object to array in JavaScript here is complete code
var co = {'yAxis':10};
var dynCharts = new Array();
for (var x=0; x<2; x++){
dynCharts[x] = co;
}
//assigning to first array only
dynCharts[0].yAxis = { 'a':'1'};
//now alert second array
alert(dynCharts[1].yAxis.a);
If you above example code first of all I've a object called co then i'm assigning that object to arrays. Now I want to change the property called yAxis of first array but it's changing the value for the yAxis object of second array too.
JSfiddle of this code is here : http://jsfiddle.net/qvKaZ/
Can somebody please help me why its happening how to do it in property way ?
Upvotes: 0
Views: 118
Reputation: 48761
One way is to use Object.create
, which will create a new object that inherits from co
.
for (var x=0; x<2; x++){
dynCharts[x] = Object.create(co);
}
An advantage is that you can update co
at any time, and all the objects that inherit from it will see the update, as long as the updated property is not shadowed on the actual object.
To handle older browsers, include this code.
if (!Object.create) {
Object.create = function(proto) {
Object.create.F.prototype = proto;
return new Object.create.F;
};
Object.create.F = function(){};
}
It's not a fully compliant substitute, but will work for basic cases as used above
Upvotes: 0
Reputation: 4350
Every object in your array is a reference to the object. If you change the object at all, all values in the array will appear to be updated. You need to make a new object or clone the existing one on each iteration of your loop.
Upvotes: 0
Reputation: 382092
You have the same object (that is the same instance) in all the cells of your array.
You need to duplicate (clone) co so that one change doesn't apply to all cells :
for (var x=0; x<2; x++){
dynCharts[x] = {yAxis:co.yAxis}; // this puts in dynCharts[x] a copy of co
}
Upvotes: 0