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?
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:
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.
Object cloning
nowadays you can clone objects with
CLONEDOLLY = JSON.parse(JSON.stringify(DOLLY));
Same caveat as below
This has the same caveat as the large blurb below: you're not really cloning the object, you're creating a new object with the same properties.
This also won't clone the prototype or any functions on the object. It works for JSON objects, but nothing else.
Exactly what I needed, thanks!!
Exactly what I needed, thanks!!
Thanks xeno
Absolutely perfect.... wish this site was the first hit by google. Your comment conversation answered my problem, and gave me some background understanding
Array duplication
There's an even simpler option, helpfully called Array.concat
Whoops
This comment came so close to getting accidentally deleted while clearing comment span. In that I had to actually restore it from backup.
Thanks!
Thanks! Simple and dumb.