1

I am trying to print a 9x9 2D JavaScript array in a grid format and I cannot get a line break to concatenate into a printable string. It prints the entire array in a single line when I want to print in a square grid. Here is the code:

function printBoard(board) {
    var toPrint = "";

    for (var i = 0; i < board.length; i++) {
        for (var j = 0; j < board.length; j++) {
         toPrint += board[i][j] + " ";
        }
        toPrint += "\n";
    }
    document.getElementById("printBoard").innerHTML = toPrint;
}

Anyone see something obvious I'm not seeing? I'm new to JavaScript so take it easy on me if its an obvious error, but I'm not just seeing it. Does the innerHTML function not print multiple lines? The HTML side of it is very simple:

<p id="printBoard"></p> 
ja08prat
  • 154
  • 10

2 Answers2

3

The newline character doesn't do anything most of the time in HTML . You need to use a linebreak element: <br />, or put everything in a preformatted element: <pre></pre>

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre

Christian Scott
  • 893
  • 7
  • 19
1

A line break in HTML is <br>

Also, your inner loop should be initialized for (var j = 0; j < board[i].length; j++). To see why, consider the array [[1, 2, 3], [1, 2 ,3]]. You current implementation would print

    1 2
    1 2

because board.length is 2.

http://jsbin.com/focofecadi/1/edit?html,js,console,output

pseudobbs
  • 214
  • 1
  • 6