【问题标题】:Why does the matrix update the index for both the columns?为什么矩阵会更新两列的索引?
【发布时间】:2021-09-16 06:14:09
【问题描述】:

我正在用 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],
    ]);
  });

错误信息:

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

【问题讨论】:

    标签: javascript unit-testing testing jestjs tdd


    【解决方案1】:

    问题出在这里:

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

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

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

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

    【讨论】:

    • 我也建议Array.from({length: size},()=&gt; ({ ship: null, attacked: false, index: -1 }))
    • 不过,Array.from 的速度要慢得多。
    • 您需要在最后一个 sn-p 中使用 .fill,因为 .map 不会遍历未填充的条目:new Array(10).map(()=&gt;1) 导致:[,,,,,,,,,]
    猜你喜欢
    • 2015-12-09
    • 2019-09-09
    • 2015-10-27
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 2014-03-13
    相关资源
    最近更新 更多