Erich Will
Erich Will

Reputation: 13

Javascript insert array in array

Source from wi2l.de/sof.html

var x = -1;
var a = new Array(9);
var i = new Array(2);

x = x + 1;
a[x] = ["a", "b"];
x = x + 1;
a[x] = ["c", "d"];
i[0] = "e";
i[1] = "f";
x = x + 1;
a[x] = i;
i[0] = "g";
i[1] = "h";
x = x + 1;
a[x] = i;

console.log(a[1] + " " + a[2] + " " + a[3]);

result is c,d g,h g,h but should be c,d e,f g,h.

Upvotes: 1

Views: 60

Answers (3)

Satoshi
Satoshi

Reputation: 16

a[2] seems to point to the memory address of i and not recover its value.

To counter this, you need to recover the value of i. You can do it this way:

a[x] = Object.values(i)

Upvotes: 0

David R
David R

Reputation: 3

The code does what it is expected to do in the contents of array a is [["a","b"],["c","d"],i,i]

Because you change the value of i to [g,h] you change it in both places. If what you wanted to do was create a copy of the array you could change

x=x+1;
a[x]=i;

to:

i[0] = "e";
i[1] = "f";
x = x + 1; 
a[x] = [...i]; //creates a new array with the contents of i
i[0] = "g";
i[1] = "h";
x = x + 1; 
a[x] = i;

Doing this results in [["a","b"],["c","d"],["e","f"],i]

Upvotes: 0

TKoL
TKoL

Reputation: 13892

i[0] = "e"; // these two lines
i[1] = "f";
x = x + 1;
a[x] = i;
i[0] = "g"; // are changing the same array as these two lines
i[1] = "h";

So when you add the array i in, and change it's value, it changes it everywhere you used that array. It doesn't make a copy or anything.

Upvotes: 1

Related Questions