1

Today I have a quick Javascript doubt. I want to create a matrix, and be able to assign and read values from it. But I'm facing an weird issue. Take a look at the following code:


    let auxTable = Array(2).fill(Array(2).fill(null));
    
    auxTable[0][0] = 1;
    auxTable[0][1] = 2;
    auxTable[1][0] = 3;
    auxTable[1][1] = 4;

The expected output, from my point of view, would be [[1,2],[3,4]]

But I'm getting [[3,4],[3,4]] as a result.

If I do only:

    let auxTable = Array(2).fill(Array(2).fill(null));

    auxTable[1][0] = 3;
    auxTable[1][1] = 4;

The result is the same, i.e., the first index seems to be ignored.

Can someone explain why this weird behavior is happening? What is the best way to work with matrices?

Thanks, friends! :)

  • Becouse of you fill first array with the second **one**. In the first array you have **two** references to only **one** second array. It's kind of reference-nature-of-js. Check this [thread](https://stackoverflow.com/q/53992415/87713) for details. – A1exandr Belan Nov 27 '21 at 06:11

0 Answers0