Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't copy the array [duplicate]

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.

like image 859
Sadashiva Madan Avatar asked Feb 21 '14 13:02

Sadashiva Madan


People also ask

How do you duplicate an array?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

Can array be copied?

Answer: There are different methods to copy an array. You can use a for loop and copy elements of one to another one by one. Use the clone method to clone an array. Use arraycopy() method of System class.

How do you copy an array in JavaScript?

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.


1 Answers

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();
like image 127
Tuyoshi Vinicius Avatar answered Sep 29 '22 10:09

Tuyoshi Vinicius