Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript object literal and array

Tags:

javascript

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?

like image 800
32423hjh32423 Avatar asked Jun 19 '26 17:06

32423hjh32423


1 Answers

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} );
like image 56
Egil Hansen Avatar answered Jun 21 '26 08:06

Egil Hansen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!