As I work on generating a two-dimensional array of objects, each object has its own X and Y coordinates. The instantiation process seems to be correct as confirmed by console logging and the position in the array aligning with the values.
However, upon logging the final array after assigning positions to instances of the object, I notice that all objects have identical X coordinates, while the Y coordinates are accurate.
let coordinates = Array(30).fill(Array(40)) // creating 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 am struggling to understand why this is happening. Despite researching bindings, scope, and alternative methods like using objects instead of classes, I am unable to resolve the issue. Addressing this problem could potentially solve other unexpected behaviors within my program. For instance, when attempting to create a maze using deep travel and recursion, setting the "Visited" property of each tile to true leads to all tiles being marked as visited, halting progression even though they were not traversed.
If anyone can shed light on what may be causing these issues, I would greatly appreciate it. It's frustratingly simple yet perplexing at the same time.
Thank you for your assistance.