简体   繁体   English

复制数组时slice()的奇怪问题

[英]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/ 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. 对于对象引用(而不是实际对象),slice将对象引用复制到新数组中。 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. 因此, slice正在复制引用,而不是对象。 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. slice()方法将数组的一部分的浅表副本返回到新的数组对象中。

For the arrays, object references are stored, so just the references get copied. 对于数组,存储对象引用,因此只复制引用。 For the String you will not observe this behaviour. 对于String,您将不会观察到此行为。

For object references (and not the actual object), slice copies object references into the new array. 对于对象引用(而不是实际对象),slice将对象引用复制到新数组中。 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. 对于字符串和数字(​​不是String和Number对象),slice将字符串和数字复制到新数组中。 Changes to the string or number in one array does not affect the other array. 对一个数组中的字符串或数字的更改不会影响另一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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