An array, in JavaScript, can be simulated through nested Arrays.
What is called line or column is merely symbolic and abstract; I specifically like to think of the lines as being the positions of the parent Array:
var minhaMatriz = [
linha0, // ainda indefinida!
linha1 // ainda indefinida!
];
But each row (so that we get an array ) is an Array itself, where each position represents a cell whose definition is the crossing of a line with a column. In this way, we can say that " lines have columns" (according to the way I like to think):
var minhaMatriz = [
[ "L0 C0", "L0 C1", "L0 C2" ],
[ "L1 C0", "L1 C1", "L1 C2" ]
];
With this, we will have a 2x3 array, that is, 2 rows by 3 columns.
As JavaScript is a dynamic typed language, in addition to the content (value) of each cell being entirely open to its choice, we do not even have to define the type; just iterate over the array to set or change the value of each column.
To iterate over the array, just iterate over the rows calls, and, within that iteration, also iterate over the columns calls. In the example below, the index i
denotes the current row, and the index j
denotes the current column:
// Troca o valor de todas as células para o inteiro 0:
for(var i = 0; i < minhaMatriz.length; i++){ // Para cada linha (índice "i")
for(var j = 0; j < minhaMatriz[i].length; j++){ // Para cada coluna (índice "j")
minhaMatriz[i][j] = 0; // Troca o valor da célula da linha "i", coluna "j".
}
}
So, to traverse only the first column of an array, we only need a single loop:
// Troca o valor de cada célula da primeira coluna para 0:
for(var i = 0; i < minhaMatriz.length; i++){
minhaMatriz[i][0] = 0; // Troca o valor da célula da linha "i", coluna 0.
}
Variable size
So far, we have created a 2D matrix (that is, has the dimensions height , which corresponds to the number of lines, and width , which corresponds to the number of columns) conceptually static, in the sense of having already been declared with the data.
It could also have been declared without any line:
var minhaMatriz = [];
Regardless of how it was declared, however, we can either edit the data within it (as already shown), we can also apply operations on the size of it.
Inserting lines
As I said earlier, the array is an Array of rows, and the rows are programmed as Cell Arrays. In this way, to add rows, simply insert a new Array of cells in Array array, through the native method push(elemento)
of array. Obs : this method always adds the " elemento
" to the end of the Array, so in the example below, the new line will be the last one:
11.11.2014 / 19:41