-1

Create a blank HTML file (create a txt file and rename the extension .html), with this entire thing in the file:

<body onload="test()"></body>

<script>
    function test() {
        var TwoDimArray = Array(4).fill(new Array("", ""))
        TwoDimArray[0][0] = "test"
        }
</script>

Open the devtools (likely F12 for most browsers), set a breakpoint at TwoDimArray[0][0] = "test", then press Step over. The problem: All elements get written when only the first should be written:

enter image description here

I tested this on chrome, firefox, and even edge, and all of them resulted in all the elements written

AAsomb113
  • 61
  • 5
  • 3
    Not a bug, you fill the outer array with multiple references to the same single inner array. – jonrsharpe Jun 16 '21 at 22:33
  • I can't find an exact duplicate for this. There is [Efficiently fill values in an array of objects in JavaScript](https://stackoverflow.com/a/58966615/691711) which might work. It's about dynamically filling though, but might fit this use case. The answer comes down to the same thing: use `.map()`. – zero298 Jun 16 '21 at 22:47

3 Answers3

1

You are filling the outer array with references to the same array. Check the reference documentation where the following is noted:

If the first parameter is an object, each slot in the array will reference that object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

puelo
  • 5,464
  • 2
  • 34
  • 62
  • Additionally, this is kind of consistent with how JavaScript works in general. https://stackoverflow.com/a/3638034/9208887 – The Fool Jun 16 '21 at 22:57
  • So, to avoid this, a loop writing an array in each element of the outer array is needed. – AAsomb113 Jun 16 '21 at 23:00
0

Use a .map() instead of .fill(). .fill() will use the same object.

const twoDimArray = new Array(4).fill(0).map(() => new Array("", ""));
twoDimArray[0][0] = "test";
console.log(JSON.stringify(twoDimArray, null, 4));
zero298
  • 25,467
  • 10
  • 75
  • 100
0

This is not a bug, as you can read on the internet with simple search the fill function put the same value on all array elements, in your case the value is object of type array which means that all the array elements are pointing to the same object so when you update the 0,0 position you actually see the change on all positions.

If you want to initial this array with different arrays you can use from function, like this: (you can also find here more options.)

    
<body onload="test()"></body>
    
    <script>
        function test() {
            var TwoDimArray = Array.from({length:10},()=> (new Array("", "")));
            TwoDimArray[0][0] = "test";
            console.log(TwoDimArray);
            }
    </script>
Yair I
  • 1,133
  • 1
  • 6
  • 9