I would like to push some element in a 2-D empty Array, and I find some problem with the push method.
var a = [[],[],[]];
a[1].push(1);
console.log(a);
//result: [ [], [ 1 ], [] ]
The above code will get the correct result, but the push method always push to all index if I use new Array method. Did I do something wrong with it?
var a = new Array(3).fill([]);
// a = [[], [], []]
a[1].push(1);
console.log(a);
//result: [ [ 1 ], [ 1 ], [ 1 ] ],
//but I think it should be [ [], [ 1 ], [] ] if I only push 1 to a[1]
The first snippet creates 3 different sub-arrays and stores them in a at a[0], a[1], a[2]. When you modify a[1], a[0] and a[2] are not effected.
The second snippet creates 1 sub-array and stores it in a 3 times at a[0], a[1], a[2]. When you modify a[1], a[0] and a[2] are modified too because they all hold the same array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With