813Copying Arrays in Javascript with slice(0)
Using Arrays in Javascript retain their values by references.
var oneArray = ["a", "b", "c"]; var anotherArray = oneArray; anotherArray[0] = "z"; console.log(oneArray, anotherArray); // ["z", "b", "c"], ["z", "b", "c"]
Ok, but let’s say you’ll need to make a copy of the array. How do you do that?
var oneArray = ["a", "b", "c"]; var anotherArray = oneArray.slice(0); anotherArray[0] = "z"; console.log(oneArray, anotherArray); // ["a", "b", "c"], ["z", "b", "c"]
If you’d really, really want you could also wrap it into a prototype function. Although the code-characters savings are minimal.
Array.prototype.copy = function() { return this.slice(0); } var anotherArray = oneArray.slice(0); //vs var anotherArray = oneArray.copy();
Minimal, but maybe contextually for self-explaining.