Archive for October, 2009

Array clone in javascript ?

There’s no such thing unfortunately, but it’s easy to replicate the same behaviour since we’ve got a handy cross-browser method called slice.
So what does the slice method do ? It allows up to two parameters to be passed in, start index and end index. If none are sent in the slice method will return a COPY of the original array, which allows us to use it as if it were a clone method. If only the first parameter is specified it will assume the full length of the array as secondary parameter. Not specifying a value will as earlier mentioned behave the same as this:

var copiedArray = theArray.slice( 0, theArray.length );
 
//this results in the same
var copiedArray = theArray.slice();

Examples:

var sourceArray = [1,2,3,4,5],
     clonedArray = sourceArray.slice();
 
alert(sourceArray.slice(1));  //will return & alert a copied array with the values 2,3,4,5 at indexes 1,2,3,4
 
alert(sourceArray.slice(1,2));  //will return & alert a copied array with the value 2 at index 0
 
sourceArray = sourceArray.slice(1,4);  //sourceArray will now contain 2,3,4
 
alert(clonedArray);  //will still alert 1,2,3,4,5 since it's a copy of the original array and not a reference.

1 Comment