We were already talking about how to multiply arrays in JavaScript and we realised that we had not explained something as simple as traversing an array with Javascript. So we couldn't let the time pass and we have started working to explain you how to do this task.
The first thing to do is to define the array in Javascript. To do this we instantiate it directly on a constant.
const matrix = [[1,2,3],[4,5,6],[7,8,9]];
Here we see that the elements of the array are themselves arrays of elements, which ends up forming the matrix.
Being an array of arrays, we will need two for loops to traverse the matrix. The first one will traverse the main array and the second one will traverse each of the secondary arrays. The arrays will go from the initial position to the length of the array, which we get through the .length
property.
In this way the two concatenated loops are as follows:
for (x=0;x<matrix.length;x++) { for (y=0;y<matrix[x].length;y++) { // Acceder al elemento } }
Inside the second loop, we can access the element via the x and y variables of the matrix.
for (x=0;x<matrix.length;x++) { for (y=0;y<matrix[x].length;y++) { console.log(matrix[x][y]); } }
This code returns the list of the elements we have traversed in the matrix. So, in order not to leave it without formatting, we are going to add a little bit of formatting in the generation of the array information. The final code will look like this:
for (x=0;x<matrix.length;x++) { text = "" for (y=0;y<matrix[x].length;y++) { text += matrix[x][y] + "t"; } console.log(text) }
I hope you found useful this simple code that explains how to traverse a matrix with JavaScript.