Skip to content Skip to sidebar Skip to footer

Javascript Create Table With For Loop And Array

I am trying to generate a table based on arrays and for loops. I have tried my best to solve this on my own With no result. In the for loop you can see that I have tried but With n

Solution 1:

First of all, your for loop does not make use of the measurement array or the year array - you're just adding the elements from the tree array. The second point - you're making a row for "Tresort" in each loop iteration.

At the end, your result will have the value of

"<tr><th>Tresort</th></tr>
<tr><th>furu</th></tr>
<tr><th>Tresort</th></tr>
<tr><th>gran</th></tr>
<tr><th>Tresort</th></tr>
<tr><th>lauvtre</th></tr>"

which is not what you want. Also, in the second line of your loop you're closing tr tag before closing the th tag, which could also cause errors.

Solution 2:

simple solution your code based (see on jsfiddle)

functiontabellOp() {
  var measurement = [ [20,31,53,89,102,117], [23,39,72,89,92,99], [4,6,8,12,15,18] ];
  var tree = ["furu", "gran", "lauvtre"];
  var year = [1915,1950,1970,1990,1992,2000];
  var tabellget = document.querySelector("#tabell");
  var row = "<tr><th> Tresort</th>";

  for (var i = 0; i < year.length; i++) {
    row += "<th>" + year[i] + "</th>";
  }
  row += "</tr>";

  for (var i = 0; i < tree.length; i++) {
    row += "<tr><th>" + tree[i] + "</th>";
    for (var j = 0; j < measurement[i].length; j++) {
      row += "<td>" + measurement[i][j] + "</td>";
    }
    row += "</tr>";
  }

  tabellget.innerHTML = row;
}
window.onload = tabellOp;

Post a Comment for "Javascript Create Table With For Loop And Array"