Taylor Mack Taylor Mack - 1 month ago 11
Javascript Question

Javascript Table with Arrays and Loops - Broken

Broken table using an 1 & 2 Dimensional Arrays with for-loops.

How can I get "loanAmount[row] to display only one time on the left most column of the table?

function print2DArrayTable(this2DArray, title)
{
//Creates the header of the table
document.write("<table border='1' cellpadding='5'>");
document.write("<tr><th colspan='8'>");
document.write("<h2>" + title + "</h2>");
document.write("</th></tr>")


//Creates the Year headers on top of the table columns.
document.write("<th></th>");
for(x=0; x<numberOfYear.length; x++)
{
document.write("<th>" +numberOfYear[x]+ "</th>");
}


for(row=0; row<this2DArray.length; row++)
{
document.write("<tr>");
for(col=0; col<this2DArray[0].length; col++)
{
document.write("<td>"+loanAmount[row]+"</td>");
document.write("<td>");
document.write(this2DArray[row][col] + "&nbsp;&nbsp;");
document.write("</td>");
}
document.write("</tr>");

}
document.write("</table>");
}/* end of print2DArraytable */


The first column is correct. but every other one is not..
Here is a picture of it.
enter image description here

Answer

Move your line that generates the first column outside of your inner loop.

for(row=0; row<this2DArray.length; row++)
  {  
     document.write("<tr>");

     // We only want to do this once per row
     document.write("<td>"+loanAmount[row]+"</td>");

     // After writing out the first column, write out the rest
     for(col=0; col<this2DArray[0].length; col++)
     {

        document.write("<td>");
        document.write(this2DArray[row][col] + "&nbsp;&nbsp;");
        document.write("</td>");
     }
     document.write("</tr>");

  }