Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push method with new Array [duplicate]

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]
like image 725
LY Huang Avatar asked Mar 22 '26 04:03

LY Huang


1 Answers

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.

like image 77
dejvuth Avatar answered Mar 23 '26 17:03

dejvuth