Nested for loop table with array

Viewed 47

I would like to have the table randomized with array. As you can see when you run it, it shows the same random number each row. I would like it to have it randomized on each cell.

here's the code:

//this is the variable that creates an array of random numbers
var random = [];
for(var i = 0; i < 100; i++){
  random[i] = Math.floor(Math.random() * 1000) +1;
}

random.sort(function(a,b){
  return a-b;});

var tabell;
tabell = "<table border='1' width='300' cellspacing='0' cellpadding='3'>";

//this is the nested for loop for creating a row
for(var i = 0; i < 10; i++){
  tabell = tabell + "<tr>";

//this is the for loop for creating the cell
  for(var j=0; j<10; j++){


     tabell += "<td>" + random[i] + "</td>";
  }

  tabell = tabell + "</tr>"
}

tabell = tabell + "</table>"
document.write(tabell);

1 Answers

You could use random[(i*10) + j]

  • When i == 0 you wolud get random[0] to random[9]
  • When i == 1 you would get random[10] to random[19]
  • ....
  • When i == 9 you would get random[90] to random[99]
Related