2

I have the following JavaScript code:

oCoord = {x: null, y: null};
var aStack = [];

oCoord.x = 726;
oCoord.y = 52;
aStack.push(oCoord);

oCoord.x = 76;
oCoord.y = 532;
aStack.push(oCoord);

oCoord.x = 716;
oCoord.y = 529;
aStack.push(oCoord);

Now this creates the following structure (an array of three objects).

Array[Object, Object, Object];

However, when I try and access the properties of each object they are all coming out the same. Why is this?

alert(aStack[0].x); // Outputs 716
alert(aStack[1].x); // Outputs 716
alert(aStack[2].x); // Outputs 716

What am I doing wrong?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
32423hjh32423
  • 3,048
  • 7
  • 44
  • 59

5 Answers5

12

You are using the same oCoord for all your coordinates objects.

Try this instead:

var aStack = []; 
aStack.push( { x: 726, y: 52} );
aStack.push( { x: 532, y: 76} ); 
aStack.push( { x: 716, y: 529} );
Egil Hansen
  • 15,028
  • 8
  • 37
  • 54
3

You are using the same reference to your object. You need to create a new one each time.

E.g.

var aStack = []; 

aStack.push( { x: 2, y: 23 }); 
aStack.push( { x: 3, y: 4 }); 
aStack.push( { x: 33, y: 2 });

Or, if you prefer the style you wrote it in, do:

var aStack = []; 

var o = {};
o.x=1;
o.y=3;
aStack.push(o); 

var o = {};
o.x=21;
o.y=32;
aStack.push(o); 

var o = {};
o.x=14;
o.y=43;
aStack.push(o); 


alert( aStack[0].x ); 
alert( aStack[1].x ); 
alert( aStack[2].x );

Note we are re-declaring with var each time to create a new instance.

D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283
  • 3
    Afaik you can't "re-declare" variables in JS, the `var` part will just be ignored and this answer would work without the extra `var`s (i.e. o = {} only). – cic Jul 09 '09 at 09:30
  • 2
    cic is right, you aren't declaring a new variable each time, instead you are using the same variable o everywhere, but assigning new valus to it. – Rene Saarsoo Jul 09 '09 at 09:58
1
var aStack = [];
aStack.push({ x: 726; y: 52 });
aStack.push({ x: 76; y: 532 });
aStack.push({ x: 716; y: 529 });
Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191
1

You are overwriting the values of x and y in oCord.

So when you say

 oCoord.x = 716;
 oCoord.y = 529;

it overwrites the previous value.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ratnesh Maurya
  • 706
  • 3
  • 10
1

Egil Hansen's answer is probably better, but you could clone the object as an alternative solution:

// Some function to clone objects (e.g. using jQuery)
function clone(o) { return $.extend(true, {}, o); }

oCoord = { x: null, y: null };
var aStack = []; 

oCoord.x = 726; 
oCoord.y = 52; 
aStack.push( clone(oCoord) ); 

oCoord.x = 76; 
oCoord.y = 532; 
aStack.push( clone(oCoord) ); 

oCoord.x = 716; 
oCoord.y = 529; 
aStack.push( clone(oCoord) );

// console.log(aStack) =>
// [Object x=726 y=52, Object x=76 y=532, Object x=716 y=529]
Community
  • 1
  • 1
cic
  • 7,310
  • 3
  • 23
  • 35