尝试使用对象建立矩阵

时间:2018-09-26 11:16:21

标签: javascript arrays matrix

gSize来自用户(4/6/8)

我想将其设为矩阵,但是我得到的是16行的数组-为什么?

我的代码是

function createBoard(gSize) {

  var board = [];
  for (var i = 0; i < gSize; i++) {
    // board.push([])
    for (var j = 0; j < gSize; j++) {
      // board[i][j] = empty
      board.push({
        posi: i,
        posj: j,
        minesAroundCount: 4,
        isShown: true,
        isMine: false,
        isMarked: true,
      })
    }
  }

  return board
}

console.log(
  createBoard(4)
);

1 个答案:

答案 0 :(得分:2)

您需要添加内部数组以获得矩阵,然后推入内部数组。

function createBoard(gSize) {
  var board = [];
  for (var i = 0; i < gSize; i++) {
    board[i] = [];                    // create nested array
    for (var j = 0; j < gSize; j++) {
      board[i].push({                 // push to the inner array
        posi: i,
        posj: j,
        minesAroundCount: 4,
        isShown: true,
        isMine: false,
        isMarked: true,
      })
    }
  }
  return board;
}

具有对象扩展功能的ES6

function createBoard(length) {
    const defaults = { minesAroundCount: 4, isShown: true, isMine: false, isMarked: true };
    return Array.from(
        { length },
        (_, posi) => Array.from(
            { length },
            (_, posj) => ({ posi, posj, ...defaults })
        )
    );
}