The Correct Way to Clone Javascript Arrays
I couldn't remember how to clone arrays in JavaScript, so I did a quick search for the answer.
I found some, uh, not-so-great answers, mainly involving writing custom copy functions that iterated over every item in the array to copy it.
Turns out there already exists a method in JavaScript 1.2+ (in other words, in all major browsers) to clone arrays. It's called, helpfully enough, slice(begin[,end]).
It returns a copy of the given slice of the array.
Or it can return the entire array.
So copying an array in JavaScript is simply:
var clone = originalArray.slice(0);
That's it. Simple. No need to iterate over the array and copy each element individually.
If you really want a clone method:
Array.prototype.clone = function() { return this.slice(0); }
Here's a simple example:
var a = [ 'apple', 'orange', 'grape' ];
b = a.slice(0);
b[0] = 'cola';
document.writeln("a=" + a + "<br>");
document.writeln("b=" + b);



What about an array of object?
Would 'slice' work with an array of objects?
Everything is an object in JavaScript
Considering that everything is an object in JavaScript, I would have to answer yes.
Wrong. in that way objects will be passed by reference, not clon
Wrong. in that way objects will be passed by reference, not cloned
So you really mean "deep copy"
So what you're really asking is there an easy way to do a deep copy. And the answer to that is "no." (Sadly, the answer to "is there a good way to do a deep copy" is also "no" if you ever include any DOM objects.)
However, an array of objects can be cloned. Just remember that it's really an array of object references, and you're creating a copy of the array of object references.
Otherwise, your best bet for a deep copy is:
function deepCopy(obj) { if (typeof obj == 'object') { if (isArray(obj)) { var l = obj.length; var r = new Array(l); for (var i = 0; i < l; i++) { r[i] = deepCopy(obj[i]); } return r; } else { var r = {}; r.prototype = obj.prototype; for (var k in obj) { r[k] = deepCopy(obj[k]); } return r; } } return obj; } var ARRAY_PROPS = { length: 'number', sort: 'function', slice: 'function', splice: 'function' }; /** * Determining if something is an array in JavaScript * is error-prone at best. */ function isArray(obj) { if (obj instanceof Array) return true; // Otherwise, guess: for (var k in ARRAY_PROPS) { if (!(k in obj && typeof obj[k] == ARRAY_PROPS[k])) return false; } return true; }Note that this will only really work on JSON objects. It sort of works on regular JavaScript objects solely because the functions from the prototype will show up in the iteration - but the cloned object won't be an "instanceof" object.
There's no real way around that because there's no JavaScript-standard way of getting the prototype from the original object.