Absolutely reference-free array copy with nested arrays

女生的网名这么多〃 提交于 2019-12-22 13:59:16

问题


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]

(example source)

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.

  • Is this approach acceptable?
  • Are there some built-in functions that I am missing?

I just can't believe I need to do all that for just copying a silly array


回答1:


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));


来源:https://stackoverflow.com/questions/10891706/absolutely-reference-free-array-copy-with-nested-arrays

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