Skip to content Skip to sidebar Skip to footer

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 ar

Solution 1:

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.

Solution 2:

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.

Post a Comment for "Weird Issue With Slice() When Copying An Array"