As explained in the comments, in accordance with the documentation, when you do Array(3,3)
, you are creating an array with 2 elements (and both elements are the number 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 matrices per se (although there are libraries for this), but you can simply create an array of arrays: first you create an array, and then you make each element of it also an array.
For this you can use Array(3)
, because according to the documentation, when only a number is passed to the constructor, this is used as the array size.
Then you loop this array, and make each element another array of 3 elements:
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 "matrix" (which is actually an array of arrays), the syntax is not used [x, y]
. First you do matriz[x]
, which returns the position array x
. And how matriz[x]
is also an array, to access the position y
of it just make 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] + "  ");
}
document.write("<br>");
}
Declaration. In Javascript we do not create an array with
Array(3, 3)
. See the documentation on MDN. And you also don’t access a position with[x, y]
, you need to create a array of array.– Woss
This documentation did not make my doubt very clear, because in a coordinate axis, I thought the syntax of the Array could be written in parentheses (). I noticed some articles here on the internet, but I couldn’t come up with any conclusions regarding this syntax made with brackets [][] which is quite different from what I learned in theory. You could put a practical example about this syntax?
– pe.Math