Extending Prototype - cloning arrays
Not long ago, I posted a JavaScript Quick Tip entitled a truly new array. As I needed this feature for one of the projects I'm working on, I decided to extend my favorite JavaScript framework (aka Prototype) so as to include it.
The code is pretty basic:
Object.extend(Array.prototype, {
clone: function(){
return [].concat(this);
}
});
and here's how you use it:
var animals = ['horse', 'dog', 'penguin'];
var mammals = animals.clone();
mammals.pop();
alert(animals); // returns 'horse, dog, penguin'
alert(mammals); // returns 'horse, dog'
It is using Prototype's Object.extend() method to add the clone() method to every instance of the Array object.
The clone() method simply creates a new Array object (using the shorthand syntax []) which it populates with the content of the array instance (referred by this) using the concat() method.
Hope you find it useful!
Update: this code is now downloadable as part of xPrototype, my tiny add-on to Prototype.
Update (Oct. 17. 2006): this code is no longer part of xPrototype as it has been added to Prototype Trunk.
Comments
-
My view on related toipic: creating arrays from array-like objects (function arguments, for example) or why Prototype’s $A is not the best implementation:
https://weblogs.sdn.sap.com/pub/wlg/4158
VS
Wed, August 16 at 18:56 PM
-
[...] Just as we liked cloning arrays we would love being able to do so with hashes. Ideally, the same method we used to clone arrays could be used to clone hashes. Unfortunately, this is not so. [...]
Wed, October 04 at 00:53 AM
-
[...] a clone() method for Array (previously explained here), [...]
Wed, October 04 at 01:46 AM