javascript - Absolutely reference-free array copy with nested arrays -
at first thought arr.slice(0) doing deep unreferenced copy, doing shallow unreferenced copy, if array contains nested arrays, they still referenced:
var = [1,2] var b = [3,4] var c = [a,b] var d = c.slice(0) d[0] === // true, means /same/ object d[0][0] = "hi!" // ["hi!", 2] the solution on links provided easy when know structure of array (just .slice(0)ing again nested arrays trick), gets complicated if don't know how structure of nested arrays is.
my first idea loop on whole thing, on levels, until fails find array object.
- is approach acceptable?
- are there built-in functions missing?
i can't believe need copying silly array
like nonnb suggests, serializations / deserialization cycle result in deep copy. this:
//a array arbitrary levels of nesting. var c = json.parse(json.stringify(a));
Comments
Post a Comment