I\'m trying to create a 2D array of certain dimensions - 26x2. I\'m doing it with 2 for loops. Then I try to change certain element but it changes whole the array column.
<for (var i = 0; i < rowsNum; i++) {
counterArray.push(colCounter);
}
What you are doing here is pushing the same reference to your row repeatedly, so your 2D array looks like this:
| ref#1 |
| ref#1 | ref#1 = [0, 0, ..., 0]
...
| ref#1 |
What you actually want, however, is something like this:
| ref#1 | ref#1 = [0, 0, ..., 0]
| ref#2 | ref#2 = [0, 0, ..., 0]
...
| ref#26 | ref#26 = [0, 0, ..., 0]
And therefore, you should create a new array before you push it in:
var colsNum = 2;
var rowsNum = 26;
var matrix = []
for(var row = 0; row < rowsNum; row++) {
var rowArray = []
for(var col = 0; col < colsNum; col++) {
rowArray.push(0);
}
matrix.push(rowArray);
}