复制数组时slice()的奇怪问题 [英] Weird issue with slice() when copying an array

查看:202
本文介绍了复制数组时slice()的奇怪问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个空数组,稍后在代码中将填充数据。但是在到达该阶段之前,会有一个部分将默认内容复制到一个临时数组,因此可以更改原始内容,然后再接收存储在副本中的相关数据。

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.

问题是当我使用slice并删除原始数组中的节时,临时数组也受到了影响。

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:

< a href = http://jsfiddle.net/Mbv6j/4/ rel = nofollow> 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.

推荐答案

这是预期的行为。看看文档
您只能得到原始数组的副本:

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


slice()方法返回的浅副本。

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.

对于字符串和数字(​​不是String和Number对象),slice将字符串和数字复制到新数组中。一个数组中的字符串或数字的更改不会影响另一数组。

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.

这篇关于复制数组时slice()的奇怪问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆