t.slez
t.slez

Reputation: 25

How to get 2d array to split into rows dynamically

I am making a tictactoe game with javascript for school and I am at a standstill. With the way I have it set up my game doesn't display as a game of tictactoe would look. Is there a way for me to split the 2d array to have 3 rows and 3 columns?

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">

Upvotes: 1

Views: 84

Answers (1)

Ori Drori
Ori Drori

Reputation: 192016

You forgot to add table rows (<tr>). In addition note that you don't have to set the innerHTML on each iteration. Collect the tags to a screen, and in the end set the innerHTML.

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();
<table id="tictable">

Upvotes: 4

Related Questions