如何让2d数组动态分割成行

时间:2016-11-20 22:19:58

标签: javascript arrays

我正在用学校的javascript进行tictactoe游戏,我处于停滞状态。按照我设置的方式设置我的游戏并不会显示为tictactoe的游戏。有没有办法让我将2d数组拆分成3行3列?

function TicTacToe() {
	this.board = [[0, 0, 0],
		[0, 0, 0],
		[0, 0, 0]
	];
	this.showhtml = toHTML;
}

function toHTML() {
	var gametable = document.getElementById("tictable");
	for (var i = 0; i < this.board.length; i++) {
		for (var j = 0; j < this.board[i].length; j++) {
			gametable.innerHTML += ("<td>" + this.board[i][j] + "</td>");
		}
	}
}

tic = new TicTacToe();
tic.showhtml();
<table id="tictable">

1 个答案:

答案 0 :(得分:4)

您忘记添加表格行(<tr>)。另外请注意,您不必在每次迭代时设置innerHTML。将标签收集到屏幕,最后设置innerHTML。

&#13;
&#13;
function TicTacToe() {
  this.board = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
  ];
  this.showhtml = toHTML;
}

function toHTML() {
  var gametable = document.getElementById("tictable");
  var htmlStr = '';

  for (var i = 0; i < this.board.length; i++) {
    
    htmlStr += '<tr>'; // row start
    
    for (var j = 0; j < this.board[i].length; j++) {
      htmlStr += ("<td>" + this.board[i][j] + "</td>");
    }
    
    htmlStr += '</tr>'; // row end
  }

  gametable.innerHTML = htmlStr;
}

tic = new TicTacToe();
tic.showhtml();
&#13;
<table id="tictable">
&#13;
&#13;
&#13;