sveti petar
sveti petar

Reputation: 3787

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?

Upvotes: 1

Views: 54

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386550

Depending how you calculate the new result, you could keep a count, like point and push tjen a new object with the values.

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

Upvotes: 1

Aleksandar Matic
Aleksandar Matic

Reputation: 799

Try this:

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

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122027

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);

Upvotes: 2

Adam
Adam

Reputation: 5233

This is how javascript works. You can do something like this:

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

Upvotes: 1

Related Questions