100 position array for 10x10 array

Asked

Viewed 434 times

1

I have a one-dimensional array of 100 positions and how to get me to draw a 10x10 matrix (table) using a loop for.

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var x= [];

for (i=0; i< 100; i++)
{
x[i] = "X";
}


var texto;

texto = "<table>";

for (i=0; i< (x.length/100); i++)
{

texto += "<tr>";

for (i=(x.length)-1; i< x.length; i++) //como resolver isso? ????
{
texto += "<td>" + x[i] + "</td>";
} 

texto += "</tr>";


}
texto += "</table>";

document.getElementById("demo").innerHTML = texto;

</script>

</body>
</html>

2 answers

2


I managed to solve the problem:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var x= [];

for (i=0; i< 100; i++)
{
x[i] = "X";
}

x[23] = "Y";
x[88] = "Z";


var texto;

texto = "<table>";

for (i=0; i < (x.length/10); i++)
{
texto += "<tr>";
for (y = (((x.length/100) * (i*10))) ; y < (((x.length/100) * (i+1)) * 10); y++)
{
texto += "<td>" + x[y] + "</td>";
} 
texto += "</tr>";

}
texto += "</table>";

document.getElementById("demo").innerHTML = texto;

</script>

</body>
</html>
  • What I did didn’t need to use auto increment inside the loop, as shown in the @Diego Felipe code. But thank you anyway.

  • Very good your code alternative. Mark your answer as solved so that others can consult in the future,

  • How do I mark as resolved?

  • Just click the green arrow below the reply counter.

  • thanks. I clicked on the arrow but a warning was displayed which I can only resolve after two days.

  • When you answer your own question, the system requires that to accept it, it must be published at least two days ago. I’m not sure what the purpose of this restriction is.

Show 1 more comment

1

Basically you will need 2 loops, one to control the vertical direction(table rows) and another internal to control the horizontal rows(columns):

var x = [];

for (i = 0; i < 100; i++) {
  x[i] = "X" + i;
};


texto = "<table>";

for (i = 0; i < (x.length);) {

  texto += "<tr>";

  for (c = 0; c < 10; c++) //como resolver isso? ????
  {
    texto += "<td>" + x[i] + "</td>";
    i++
  }

  texto += "</tr>";


}
texto += "</table>";
document.getElementById("demo").innerHTML = texto;
<div id="demo"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.