Javascript has no way for you to directly define the size of an array as it does in java with new int[4][4]
. However you can start by defining the initial array with :
new Array(tamanho)
That creates a logo array with a certain amount of elements, which represent the lines. Then scroll through each of the generated rows to create the columns.
The printing part is very similar to the one you have in java by just changing the int
and the System.out
, for let
and console.log
respectively.
Example:
let m = new Array(4).fill(0); //criar as linhas e preencher com zeros
m = m.map(linha => new Array(4).fill(0)); //criar as colunas e preencher com zeros
for (let i = 0; i < m.length; i++){
let escrita = "";
for (let j = 0; j < m[i].length; j++){
escrita += m[i][j] + " ";
}
console.log(escrita);
}
To be compact I created the columns at the expense of map
that mapped each unique value on the line by a new array of size four filled with zeros. This padding was done at the expense of fill
.
Note that the example does not have the equivalent of System.out.print
that does not change line as it is not possible to use the console.log
without changing lines. However, in Node can write without changing lines with:
process.stdout.write(m[i][j] + " ");
Which may be an alternative to the example, I just used console.log
to be more generic and executable here on live snippet.
Your question is with javascript tag instead of java. Be careful.
– Rafael Cavalcante