I need to create a copy of an array so that I can do modification on one array without affecting the other.
for example:
var a = [[1],[2],[3]];
var b = a.slice(0);
b[1].push(100);
b // [[1],[2, 100],[3]];
a // expect: [[1],[2],[3]]; , actual: [[1],[2, 100],[3]];
I have also tried:
var b = new Array(a);
but this puts all [1],[2],[3] to index 0 in the new array.
What am I missing here?
Thanks guys!
slice()method returns a shallow copy [...].b = JSON.parse(JSON.stringify(a))this will do some kind of a "deep copy", then you can modifybwithout messinga.