Weird issue with slice() when copying an array

别说谁变了你拦得住时间么 提交于 2019-12-24 23:24:55

问题


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.


回答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.




回答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.



来源:https://stackoverflow.com/questions/21604636/weird-issue-with-slice-when-copying-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!