I've been trying to generate a two dimensional array of objects. Each object contains it's own internal position in the array in two variables called X and Y. When I instantiate the object, I can see through console logging that it's being instantiated with the proper X and Y values, this can also be validated through the fact that position in the array corresponds perfectly to those values.
However, when I log the final array after iterating through and saving each position in the array two an instance of the object, they have identical X coordinates, yet the Y coordinates are perfect.
let coordinates = Array(30).fill(Array(40)) // just creates an empty two dimensional array.
class Tile {
constructor(x,y){
this.x = x;
this.y = y;
}
}
for (let x = 0; x < coordinates.length; x++) {
for (let y = 0; y < coordinates[x].length; y++) {
console.log({x,y}) // logs {x: 0, y: 0} -> {x: 29, y:39}
coordinates[x][y] = new Tile(x,y)
}
}
console.log(coordinates) // logs two dimensional array with {x: 29, y:0} -> {x: 29, y:39}
I'm going mentally crazy trying to figure out why it does that. I've tried researching bindings, scope, objects instead of classes and I cannot find a way around it. I believe figuring this out will result in solving several of my problems, as I've run into other properties on the actual Tile class being randomly set despite not touching it at all. I am referring to creating a maze using deep traveling and recursion, and having each tile contain a property called "Visited" and setting it to true once it's been traversed once.
When doing that, I run into that my maze suddenly stops as it decides that every tile around it has been "visited" as they are all equal to true, yet I've never touched them.
Anything that you guys would have that would explain what I am running into would be helpful, it's no doubt something really simple and stupid.
Thank you in advance.
for (let y = 0; x < coordinates[x].length; y++) is your problem. Your loop definitely cannot work if you are comparing to X for your Y loops, it won't ever get out.