0

I tried to create a 2-dimensional array in javascript. (Actually, the code is written in typescript and will be used to style DOM Elements with Angular2 but, as far as I am concerned, it shouldn't have any effect on the result in this case.)

First way:

arrayi = Array(10).fill(Array(20).fill(-1))

Second way:

array = [];
for(var i: number = 0; i < 10; i++) {
    array[i] = [];
    for(var j: number = 0; j< 20; j++) {
          array[i][j] = -1;
    }
}

If I call array[1][2] = 2; it does what I expected, what means setting one element in the 2-dimensional array to 2.

However, if I call arrayi[1][2] = 2; every element arrayi[x][2] will be set to 2. (With x element {0,1,2,...,9})

 

Why is that? I don't understand it. So it would be nice if someone could explain it to me.

The arrays are defined as array: number[][] and arrayi: number[][] in typescript.

oRookie
  • 265
  • 2
  • 4
  • 13
  • @evolutionxbox As the post states: if I call `arrayi[1][2] = 2;` every element `arrayi[x][2]` will be set to 2. (With x element {0,1,2,...,9}) – oRookie May 12 '17 at 11:07

2 Answers2

5

arrayi = Array(10).fill(Array(20).fill(-1)) fills with the same array.

You can even rewrite it like this

const arr1 = Array(20).fill(-1)

const arrayi = Array(10).fill(arr1)

console.log(arrayi.every(item => item === arr1)) //true
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • So... when I do `arr = Array(2).fill([1,2,3])` it is pseudo for `temp = [1,2,3]; arr = [temp, temp]`? Got it now I guess. It is because the array will be linked instead of duplicated right? Thank you very much. – oRookie May 12 '17 at 11:13
  • Kinda. It uses the same value for every index. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill – Yury Tarabanko May 12 '17 at 11:16
1

The reason is that you create one instance of array with 20 elements and put this single instance into each element of root array

Random
  • 3,807
  • 2
  • 30
  • 49