Why JavaScript changes values of whole the array column?

后端 未结 1 897
你的背包
你的背包 2021-01-29 12:45

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.

<
相关标签:
1条回答
  • 2021-01-29 13:31
    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);
    }
    
    0 讨论(0)
提交回复
热议问题