为什么矩阵更新两列的索引?

Why does the matrix update the index for both the columns?

我正在用 JS 为战舰游戏构建游戏板,这是它的当前结构:

export default class Gameboard {
  constructor(size) {
    this.grid = this.#createMatrix(size);
  }

  #createMatrix(size) {
    const mat = new Array(size);
    for (let i = 0; i < size; i++) {
      // ship - for ship object if it exists, attacked - isAttacked?,
      // index - relative placement of ship tile wrt whole ship, if it exists
      mat[i] = new Array(size).fill({ ship: null, attacked: false, index: -1 });
    }
    return mat;
  }

  /**
   * @param {Ship} ship to be placed
   * @param {int} x starting x coordinate of ship placement
   * @param {int} y starting y coordinate of ship placement
   */
  placeShip(ship, x, y) {
    for (let i = 0; i < ship.length; i++) {
      
      this.grid[x][y]["ship"] = ship;
      this.grid[x][y]["index"] = i;
      console.log(this.grid[x][y]);
      y++; //move to next column for next tile placement

    }
  }
}

我不明白为什么下面的水平放置船的测试失败了:

it("places ships", () => {
    const gameboard = new Gameboard(2);
    const ship = new Ship(2);
    gameboard.placeShip(ship, 0, 0);

    expect(gameboard.grid).toEqual([
      [
        { ship: ship, index: 0, attacked: false },
        { ship: ship, index: 1, attacked: false },
      ],
      [defaultObj, defaultObj],
    ]);
  });

错误信息:

似乎在循环时,两列的对象都得到了更新,但我只想更新一列的对象。

问题出在这里:

new Array(size).fill({ ship: null, attacked: false, index: -1 })

在那里,您正在创建 一个“ship”对象,并且您正在用对该对象的引用填充数组。

您也可以这样做,为每个条目创建一艘新船:

new Array(size).fill().map(() => ({ ship: null, attacked: false, index: -1 }));