节点js将2d数组显示为网格

时间:2017-02-04 09:20:38

标签: javascript arrays node.js 2d conways-game-of-life

这里是一个代码,用于制作一个2d数组,用作node.js中conways生命游戏的板。我在显示电路板时遇到问题。输出看起来像这样。

['-','-','-'] 
['-','-','-']
['-','-','-']

然而我希望它看起来像这样

---
---
---

这是现在的代码。有没有人有任何建议?

var createBoard = (width, height) => {
    board = [];
    row = [];
    for (var i = 0; i < width; i++) {
        for (var j = 0; j < height; j++) {
            row.push("-");
        }
        board.push(row);
        row =[];
    }
    return (board);
}

var displayBoard = (board) =>{
    for (var i = 0; i < board.length; i++) {
        console.log(board[i]);
    }
}

gameBoard = createBoard(3,3);
displayBoard(gameBoard);

2 个答案:

答案 0 :(得分:1)

您需要join数组元素才能形成字符串。

var createBoard = (width, height) => {
    board = [];
    row = [];
    for (var i = 0; i < width; i++) {
        for (var j = 0; j < height; j++) {
            row.push("-");
        }
        board.push(row);
        row = [];
    }
    return (board);
}

var displayBoard = (board) => {
    for (var i = 0; i < board.length; i++) {
        console.log(board[i].join(""));
    }
}

gameBoard = createBoard(3, 3);
displayBoard(gameBoard);

答案 1 :(得分:0)

要解决您的问题,您应该遍历数组并将其添加到字符串中,如下所示:

var displayBoard = (board) =>{
   var buffer = '';
   for (var i = 0; i < board.length; i++) {
      for (var x = 0; x < board[i].length; x++) {
        buffer += board[i][x];
      }
      buffer += '\n';
   }
   console.log(buffer);
}

这应该像这样打印出来:

---
---
---