A question about arrays

        function makeRow(v=0){
            const array = new Array(3);
            array.fill(v);
            return array;
        }

        function makeMatrix(v = 0){
            const array = new Array(3)
            array.fill(makeRow(v))

            return array;
        }

        const a = makeMatrix()
        a[0][1]=2
        console.log(a)
        /*
        [
          [0,2,0],
          [0,2,0],
          [0,2,0]
        ]
        */
        

as in the code above, why did I only manipulate item 0 of a, but the result is that each item has been changed
for a big solution

Mar.12,2021
The

array is a reference type. What makeRow (v) returns is actually const array = new Array (3); the address of the array in memory is taken three times by the fill method, so no matter which one is changed, the three will change.


because you only makeRow once, and every row in the matrix refers to the same array, changing the value in the matrix is equivalent to changing a

in the row.
Menu