So let me just start out by saying that I don't have much experience with Javascript. If someone could give me a basic explanation, that would be great.
Anyways, I want to take a two dimensional matrix and print it on the screen. This is my code so far:
function matrixToString(arr) { returnString = ""; for (var i = 0; i < arr.length; i++){ for (var j = 0; j < arr[i].length; j++){ returnString += Math.round(arr[i][j]*10000)/10000 + ' '; } returnString += "\n"; } return returnString } So when I call alert(matrixToString(n)), it works as expected. However, when I use document.write(matrixToString(n)), it basically puts everything on one line and prints that line. The same applies if I put the string into a div and append the div.
I guess my question is basically how do I put multi-line outputs to HTML in javascript.
13 Answers
Is your multiline requirement only for presentation purpose? If so, then you just need to add '
' to the end of each line. '\n' does not work when rendering HTML. Instead just replace:
returnString += "\n"; with
returnString += "<br/>"; 0in you code just replce \n with "br" like this
function matrixToString(arr) { returnString = ""; for (var i = 0; i < arr.length; i++){ for (var j = 0; j < arr[i].length; j++){ returnString += Math.round(arr[i][j]*10000)/10000 + ' '; } returnString += "<br>"; } return returnString } this works for my case
document.write is outdated and hence try directly manipulate DOM.
For example:
<div></div> JS:
document.getElementById('demo').innerHTML = matrixToString(n); Also with reference to this answer,
It depends on what you're doing with the text, but my guess is you're rendering it as Html. In that case, you should be using a
<br />tag instead of a \n.
so use returnString += "<br />"; to solve your problem.