简体   繁体   中英

Weird issue with slice() when copying an array

I have an "empty" array that will be populated with data later in the code. But before it reaches that stage there's a section where the default content is copied to a temporary array, so the original can be changed and later receive the relevant data that was stored in the copy.

The problem is when I use slice and delete the section in the original array, the temporary one is affected as well.

var array1 = [["text", [[[1,2],[3,4],[5,6]]], 0]];
var array2 = array1[0].slice(0);

//alert(array2[1][0]) // Output: 1,2,3,4,5,6
array1[0][1][0] = new Array();
//alert(array2[1][0]) // Output:

http://jsfiddle.net/Mbv6j/4/

I can use a workaround to copy each section of the array separately rather than all at once, but I still would like to understand why this is happening.

Taken from here :

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.

My guess is that since your array contains arrays of arrays, they are probably being represented as object references; thus, slice is copying the references, not the objects. It only does a shallow copy, not a deep copy. If the items in your array weren't objects, you wouldn't encounter this problem.

This is expected behaviour. Have a look at the documentation . You only get a shallow copy of the original array:

The slice() method returns a shallow copy of a portion of an array into a new array object.

For the arrays, object references are stored, so just the references get copied. For the String you will not observe this behaviour.

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 and numbers (not String and Number objects), slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM