javascriptarraysdimensional

2 dimensional array of class objects in Javascript


Trying to make an array of class objects in JS. I don't know how Javascript handles this but instead of a 10x10 grid, all numbers are set to 10 instead of the i and j values I want to assign.

class Box {
  constructor(width, height, x, y, inside) {
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
    this.inside = inside;
  }

  getHeight() {
    return this.height;
  }

  setHeight(newHeight) {
    this.height = newHeight;
  }
  let boxes = [
    []
  ];
  let testBox = new Box(1, 1, 1, 1, "Test")

  for (let i = 0; i < 11; i++) {
    for (let j = 0; j < 11; j++) {
      boxes[i[j]] = new Box(i, j, i, j, "Test");
    }
  }

  console.log(testBox.getHeight()); //Working Example
  console.log(boxes[3[3]].getHeight()); //outputs 10?
  console.log(boxes[4[6]].getHeight()); //outputs 10?


Solution

  • An example of what i wrote about in the comments

    class Box {
      constructor(width, height, x, y, inside) {
        this.width = width;
        this.height = height;
        this.x = x;
        this.y = y;
        this.inside = inside;
      }
    
      getHeight() {
        return this.height;
      }
    
      setHeight(newHeight) {
        this.height = newHeight;
      }
    }
    
    let boxes = [];
    
    for (let i = 0; i < 11; i++) {
      for (let j = 0; j < 11; j++) {
        boxes[i] = [...(boxes[i] ? boxes[i] : []),
          new Box(i, j, i, j, "Test")
        ];
      }
    }
    
    console.log(boxes[3][3].getHeight());
    console.log(boxes[4][6].getHeight());