Read array elements and print them

3

I created an algorithm that received a single variable with 9 different records that would display these values typed in matrix form (table). But by displaying the result, you are only returning the last three values in three rows in a row.

var numero = Array(3,3);
  var x,y;
  for (x = 0; x < 3; x++) {
    for (y = 0; y < 3; y++) {
      numero[x,y] = parseInt(prompt("Digite o "+[y+1]+"º número da "+[x+1]+"º coluna"));
    }
  }
  for (x = 0; x < 3; x++) {
    for (y = 0; y < 3; y++) {
      document.write(numero[x,y]+"&nbsp&nbsp");
    }
    document.write("<br>");
  }

In this case, what would be the most correct way to display the 9 values that the user typed correctly and in array form?

    
asked by anonymous 11.12.2018 / 22:47

1 answer

2

As explained in comments , according to documentation , when you do Array(3,3) , you are creating an array with 2 elements (and both elements are 3 ):

let arrayCom2Elementos = Array(3, 3);
// array com 2 elementos
console.log(arrayCom2Elementos); // [3, 3]
// tamanho do array
console.log(arrayCom2Elementos.length); // 2

In native JavaScript there are no actual arrays (though there are libraries for this ), but you can simply create an array of arrays: you first create an array, and then make each array element an array as well.

For this you can use Array(3) , because according to documentation , when only one number is passed to the constructor, this is used as the array size.

Then you loop this array, and make each element another 3-element array:

let matriz = Array(3); // array com 3 elementos

// cada elemento é outro array com 3 elementos
for (let i = 0; i < matriz.length; i++) {
  matriz[i] = Array(3);
}
console.log(matriz); // cada elemento é um array de 3 elementos

Another detail is that, to access the elements of the "array" (which is actually an array of arrays), the [x, y] syntax is not used. First you do matriz[x] , which returns the array of position x . And since matriz[x] is also an array, to access the y position, just do matriz[x][y] .

In short, your code would look like this:

let dimensao = 3; // dimensão da matriz (assumindo que ela é uma matriz quadrada)
let matriz = Array(dimensao); // array com 3 elementos

// cada elemento é outro array com 3 elementos
for (let i = 0; i < matriz.length; i++) {
  matriz[i] = Array(dimensao);
}

let linha, coluna;
for (linha = 0; linha < dimensao; linha++) {
  for (coluna = 0; coluna < dimensao; coluna++) {
    matriz[linha][coluna] = parseInt(prompt("Digite o " + (linha + 1) + "º número da " + (coluna + 1) + "º coluna"));
  }
}

for (linha = 0; linha < dimensao; linha++) {
  for (coluna = 0; coluna < dimensao; coluna++) {
    document.write(matriz[linha][coluna] + "&nbsp&nbsp");
  }
  document.write("<br>");
}
    
12.12.2018 / 12:30