1

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.

1
  • 1
    it's because "a" store the array "i" not his value. "a" store the reference so if you change it the value change too. If you want to transfer the value and not the array you need to store the value, for example with spread syntax a[x] = [...i] Commented Feb 19, 2020 at 17:35

3 Answers 3

1
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.

Sign up to request clarification or add additional context in comments.

4 Comments

but i transfer the value from i to a
It worths to notice that everything in Javascript is a reference, except String, Number, Boolean and Symbol. Everything includes literal objects, functions, literal arrays, Maps, etc..
@ErichWill no, you didn't 'transfer the value from i to a', you put i in a, and then you put i in a again.
You can overcome this by destructuring the array you're trying to add with: a[x] = [...i]
0

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)

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.