3

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]
LY Huang
  • 33
  • 4

3 Answers3

4

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.

dejvuth
  • 6,986
  • 3
  • 33
  • 36
0

Used like this, fill() puts your value in every indexes in your array. To use it as you want, you should try fill(value, start, end) where start is the first index you want to fill with value, and end is the last.

BDeliers
  • 74
  • 1
  • 12
0

That's correct. According to the docs: The fill() method fills all the elements ... with a static value.

Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47