jovan jovan - 2 months ago 5
Javascript Question

In a loop, all array elements get value of the last one

I have the following:

var travel_path=[];
var point={
"left": 0,
"top": 0
};
while(/*some condition here*/){
point.left+=3;
point.top+=5;
travel_path.push(point);
}
console.log(travel_path);


Now, if the
while
loop runs for 10 iterations, instead of getting the incremented values of
left
and
top
in each element, I get 10 elements with the same value of
{"left": 30, "top": 50}
.

So it seems that, even though I'm using push to append elements to the end of the array, it's somehow updating all the previous elements as well.

Any ideas how I can resolve this?

Answer

You can create clone of object in each iteration of loop with Object.assign() and push that object to array.

var travel_path = [];
var point = {
  "left": 0,
  "top": 0
};
var i = 0;

while (i++ < 5) {
  point.left += 3;
  point.top += 5;
  travel_path.push(Object.assign({}, point));
}
console.log(travel_path);