This question already has an answer here:
In this plunk I have an example of an array of objects a
that I copy with slice()
to b
. I alter one of the objects in a
but it changes also b
. Isn't slice
supposed to copy the array, including its contents? I need a
and b
to have different pointers.
Javascript
var a = [{x1:1, x2:2}, {x1:3, x2:4}]; var b = a.slice(); a[1].x1 = 5; console.log(b[1]);
this prints:
x1: 5 x2: 4
From MDN:
For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
For strings, numbers and booleans (not String, Number and Boolean objects), slice copies the values into the new array. Changes to the string, number or boolean in one array does not affect the other array.
Performing a deep copy on objects in the array is difficult, but this answer suggests a way to do it, as long as your array only contains JSON-serializable content:
var clonedArray = JSON.parse(JSON.stringify(originalArray));
You can try to do Deep copy with jQuery:
var b = $.extend(true,{},a);
This does a proper deep copy of all your variables.