I want to write some JavaScript to create a simple HTML table from an array that just contains numbers:
var array = [1,2,3,4,5,6,7,8,9,10];
The table should look like this:
1 2 3 4 5
6 7 8 9 10
But the JavaScript code should be dynamic depending on the arrays size (always a factor of 5 though).
I've tried a lot of stuff but it never works the way i want it to. What would be the easiest way to achieve this?
This is one of my tries.
var tableStart = "<table border>";
for (i = 0; i < arraySize/5; i++){
var tableMiddle = "<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>"
if (arraySize/5 >= 2) {
tableMiddle = tableMiddle + tableMiddle;
}
};
var tableEnd = "</table>";
var table = tableStart.concat(tableMiddle, tableEnd);
as well as
var result = "<table border=1>";
for(var i=0; i<2; i++) {
result += "<tr>";
for(var j=0; j<array.length; j++){
result += "<td>"+array[i]+"</td>";
}
result += "</tr>";
}
result += "</table>";
this one just results in two values of the array being displayed though a lot of times.