Reputation: 770
so I just came across this, but could anyone explain it to me, why is this phenomenon present here? I didn't find any help online...
1.So if I were to get the following two arrays:
let a = [];
let b = ['','',''];
2.and then push array b
into array a
three times:
a.push(b);
a.push(b);
a.push(b);
3.but then when I try to change the first element of the first array like so:
a[0][0] = 'foo';
4.then all the first element of ALL the arrays change, not just the first one, as console.log(a)
outputs:
(3) [Array(3), Array(3), Array(3)]
0: Array(3)
0: "foo"
1: ""
2: ""
1: Array(3)
0: "foo"
1: ""
2: ""
2: Array(3)
0: "foo"
1: ""
2: ""
I would like to ask, why does this happen and in what way could I change an element based on its index inside of array a
Upvotes: 0
Views: 42
Reputation: 9807
b is a pointer to a mutable array, changing the array it points to will cause the other places you point to it to update as well.
You would either push copies of b into the array or create a modified copy of b when trying to mutate the value it points to.
Upvotes: 2
Reputation: 208
if you console.log(b)
, you'll see that as well.
Try doing b[1] = "test"
then check the value of a
and you'll see all the b
's that were pushed into there have test
in them too.
b
is a reference so anytime you change the value of it, you are altering the places it is referenced to.
Upvotes: 1
Reputation: 1493
Because you're passing b
which is just a reference to an object. To have the behavior you want, change your code to be like this:
a.push(b.map((x) => x))
For more see this page.
Upvotes: 1