0

I think its supposed to be simple, but somehow, I don't get what I'm doing wrong.

I have this code:

var currentPosition = {
    x:10000,
    y:10000
};

var directions = "v>v<";
var housesVisited = [{x:10000, y:10000}];

function createHouseCoordinates(data){
    for(var x = 0; x<4; x++){
        if(data[x]=="^"){
           currentPosition.x += 1;  
        } else if(data[x]=="v"){
           currentPosition.x -= 1;
        } else if(data[x]==">"){
           currentPosition.y += 1;
        } else if(data[x]=="<"){
           currentPosition.y -= 1;  
        }
    housesVisited.push(currentPosition);
    }
}

createHouseCoordinates(directions);
console.log(housesVisited);

It is supposed to take directions in the form of symbols, modify the current location, and create an array of objects that lists all locations that were visited. The result of the above, when I run it, gives me this (basically the end position):

[ { x: 10000, y: 10000 },
{ x: 9998, y: 10000 },
{ x: 9998, y: 10000 },
{ x: 9998, y: 10000 },
{ x: 9998, y: 10000 } ]

I was expecting:

[ { x: 10000, y: 10000 },
{ x: 9999, y: 10000 },
{ x: 9999, y: 10001 },
{ x: 9998, y: 10001 },
{ x: 9998, y: 10000 } ]

What am I doing wrong? What should I read up on to understand this better..? Thanks in advance!

Vera
  • 233
  • 2
  • 5
  • 12

1 Answers1

2

currentPosition is an object. When you're making changes to it (eg currentPosition.x += 1), you're always changing that same object.

You then push it into an array, but what you're actually pushing is a reference to that object, so all the elements of the array are pointing at the same underlying object.

To fix your code, you need to clone the object information into a new object as you push it into the array:

housesVisited.push({x: currentPosition.x, y: currentPosition.y});
James Thorpe
  • 31,411
  • 5
  • 72
  • 93