4 ms·
It's not just naive though, it's wrong; it won't even give you new objects although it seems like it's meant-to: a = [1, {foo: "bar"}]; b = a.slice(0);
by drodgers 9y ago
It's not just naive though, it's wrong; it won't even give you new objects although it seems like it's meant-to:
a = [1, {foo: "bar"}];
b = a.slice(0);
b[1].foo = "baz";
console.log(a)
> [1, {foo: "baz"}]
console.log(b)
> [1, {foo: "baz"}]
A naive implementation would do this:
case '[object Array]' : clone[key] = value.map((item) => deepClone(item)); break
And would thus be slower.
- ricardobeat 9y agoWe are in agreement here. My suggestion was to make the deepClone method also take arrays, and walk through them copying values in the for loop (significantly faster than map). Again, I linked to a full implementation at the end; was more commenting on the lack of this particular approach, wrote this on the spot as an example.