完全免费的参考阵副本嵌套数组 [英] Absolutely reference-free array copy with nested arrays
问题描述
起初我还以为 arr.slice(0)
在做一个的深的未引用的副本,但它实际上是做只是一个的浅的未引用的副本,因此如果数组包含嵌套的数组,<一个href=\"http://stackoverflow.com/questions/10458356/unreferenced-array-not-so-unreferenced-after-slice\">they仍然引用:
At first I thought arr.slice(0)
was doing a deep unreferenced copy, but it is actually doing just a shallow unreferenced copy, so if the array contains nested arrays, they are still referenced:
var a = [1,2]
var b = [3,4]
var c = [a,b]
var d = c.slice(0)
d[0] === a // true, which means it is the /same/ object
d[0][0] = "Hi!"
a // ["Hi!", 2]
<子> (例如源)
上提供的链接的解决方案是相当容易的,当你知道数组结构(就像 .slice(0)
ING再嵌套数组会做的伎俩) ,但它变得复杂了,如果你不知道的嵌套数组的结构如何。
The solution on the links provided is fairly easy when you know the structure of the array (just .slice(0)
ing again the nested arrays will do the trick), but it gets complicated if you don't know how the structure of the nested arrays is.
我的第一个想法是对整个事情循环,在所有层面上,直到它未能找到阵列对象。
My first idea is to loop on the whole thing, on all levels, until it fails to find an array object.
- 是这种方法是否可以接受?
- 是否有一些内置的功能,我很想念?
我简直不敢相信,我需要做的一切,只是复制一个愚蠢的阵列
I just can't believe I need to do all that for just copying a silly array
推荐答案
像nonnb表明,一个序列化/反序列化周期将导致深拷贝。你可以做这样的:
Like nonnb suggests, a serializations / deserialization cycle will result in a deep copy. You could do it like this:
//a is some array with arbitrary levels of nesting.
var c = JSON.parse(JSON.stringify(a));
这篇关于完全免费的参考阵副本嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!