简体   繁体   English

换行符不会串联

[英]Line Break Won't Concatenate

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. 我试图以网格格式打印9x9 2D JavaScript数组,但无法换行以连接成可打印的字符串。 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. 我是JavaScript的新手,因此,如果它是明显的错误,请对我轻松一点,但我不仅看到它。 Does the innerHTML function not print multiple lines? innerHTML函数不打印多行吗? The HTML side of it is very simple: HTML的一面非常简单:

<p id="printBoard"></p> 

The newline character doesn't do anything most of the time in HTML . 在HTML中,换行符大部分时间都不起作用。 You need to use a linebreak element: <br /> , or put everything in a preformatted element: <pre></pre> 您需要使用换行符: <br /> ,或将所有内容放入预格式化的元素: <pre></pre>

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

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

A line break in HTML is <br> HTML中的换行符是<br>

Also, your inner loop should be initialized for (var j = 0; j < board[i].length; j++) . 另外,您的内部循环应初始化for (var j = 0; j < board[i].length; j++) To see why, consider the array [[1, 2, 3], [1, 2 ,3]] . 要了解原因,请考虑数组[[1, 2, 3], [1, 2 ,3]] You current implementation would print 您当前的实现将打印

    1 2
    1 2

because board.length is 2. 因为board.length是2。

http://jsbin.com/focofecadi/1/edit?html,js,console,output http://jsbin.com/focofecadi/1/edit?html,js,控制台,输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM