-1

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>

9
  • 2
    You are pushing the same rowCounters into your array. Keep in mind that rowCounter is a reference to your array. Commented Apr 29, 2017 at 23:15
  • So counterArray is not a 2d array? Commented Apr 29, 2017 at 23:24
  • It is, but your rows are all referencing the same row. Commented Apr 29, 2017 at 23:25
  • Is there a way to assign not the refference to array but it's values? Commented Apr 29, 2017 at 23:32
  • I'll post an answer. Commented Apr 29, 2017 at 23:35

1 Answer 1

2
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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.