Why JavaScript changes values of whole the array c

2020-05-10 06:42发布

问题:

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.

Can anybody explain why it happens?

function convertTable() {
                var colsNum = 2;
                var rowsNum = 26;
                var rowCounter = [];
                for (var i = 0; i < colsNum; i++) {
                    rowCounter.push(0);
                }
                var counterArray = [];
                var colCounter = rowCounter;
                for (var i = 0; i < rowsNum; i++) {
                    counterArray.push(colCounter);
                }
                document.write(counterArray);
                document.write("<br>");
                counterArray[0][0] = 1;
                counterArray[0][1] = 2;
                counterArray[1][0] = 10;
                counterArray[1][1] = 20;
                document.write(counterArray);
            }
<!DOCTYPE html>
<html>
    <body onload="convertTable()"></body>
</html>

回答1:

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);
}