16

I can't copy the array.

var Mycollection = new Array("James", "John", "Mary");
var Mycollection2 = Mycollection;

Any change made in the first array is also taken in the second.

Mycollection.pop();
console.log(Mycollection.toString()) // ["James", "John"]
console.log(Mycollection2.toString())// ["James", "John"]

However, this does not occur when I use variables of text type.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sadashiva Madan
  • 203
  • 1
  • 8

4 Answers4

5

Arrays are objects, unlike the primitive types like string, int, etc ... variables that take objects correspond to references (pointer) for objects, rather than the object itself, so different variables can reference the same object. Variable of primitive type (string, int, etc.) are associated to values​​.

In your case you will have to clone your object array for have the same values​​.

var Mycollection = new Array("James", "John", "Mary");
var Mycollection2 = Mycollection.slice();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tuyoshi Vinicius
  • 861
  • 8
  • 22
2

JavaScript passes the array by reference, to have separate arrays do:

var Mycollection = new Array("James", "John", "Mary");
var Mycollection2 = Mycollection.slice();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Moritz Mahringer
  • 1,240
  • 16
  • 28
2

You are actually copying a reference in your code,

var Mycollection = new Array("James", "John", "Mary");
var Mycollection2 = Mycollection; // Makes both Mycollection2 and Mycollection refer to the same array.

Use the Array.slice() method which creates a copy of part/all of the array.

var Mycollection1 = new Array("James", "John", "Mary");
var Mycollection2 = Mycollection.slice();

Mycollection1.pop();
console.log(Mycollection1.toString()) // ["James", "John"]
console.log(Mycollection2.toString()) // ["James", "John", "Mary"]

DEMO

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Deepak Ingole
  • 14,912
  • 10
  • 47
  • 79
1

Just use:

var Mycollection2 = Mycollection.slice(0);

to copy the array.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
andrew
  • 9,313
  • 7
  • 30
  • 61