1
var a = [], b = [];
a.push('a');
a.push('b');
a.push('c');
b = a;
b.push('d');
console.log(a);

Why is a = ["a", "b", "c", "d"] ?, how to avoid this cross reference when doing b=a; I would like just to have 2 separates objects, independants

and at the end a = ["a", "b", "c"], and b = ["a", "b", "c", "d"]

  • You need to clone the array to have separate objects http://stackoverflow.com/questions/597588/how-do-you-clone-an-array-of-objects-in-javascript – Miquel Mar 07 '12 at 10:42

5 Answers5

1

When you assign a to b, you are actually assigning a reference to a. So any change made to b will also affect a. To do what you really wanted, try:

b = [].concat(a);

which will make an actual copy of a.

Charles Anderson
  • 19,321
  • 13
  • 57
  • 73
1

In JS arrays are also objects (instance of Array object) and as such objects in JS are assigned by reference not by value, so when you do:

b = a

b is now assigned by reference to a, hence it will affect the a array.

To do what you want to do, you can do:

b = a.slice();

Here is an example:

var a = [], b = [];
a.push('a');
a.push('b');
a.push('c');
b = a.slice();
b.push('d');
console.log(a);

Result:

[a, b, c]
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
0

Because variables reference objects, they do not copy them.

You can use

var a = [], b = [];
a.push('a');
a.push('b');
a.push('c');
b = a.slice();
b.push('d');
console.log(a);
jgauffin
  • 99,844
  • 45
  • 235
  • 372
0

Because assignment does not copy variable content. (See the related Is this a variable scoping bug in NodeJS or do I just need more sleep question.)

For arrays, you could use concat to create a (shallowly) copied array:

a = [1,2,3]
b = [].concat(a)
b.push(4)

... or sliceas the other answers say.

Community
  • 1
  • 1
AKX
  • 152,115
  • 15
  • 115
  • 172
0

Once you do b = a both a and b point to the same array in memory; you need to push the elements to both a and b separately, or once you push elements to a you can loop through it and push the same to b, e.g.

for ( var i = 0; i < a.length; i++ ){ b.push( a[i] ); }
scibuff
  • 13,377
  • 2
  • 27
  • 30