Javascript Array clone()
/**/*w ww. j av a2 s. co m*/ * Makes a shallow copy of the array. * * @method Array.prototype.clone * @return {Array} A shallow copy of the array */ Array.prototype.clone = function() { return this.slice(0); };
Array.prototype.clone = function () { var newArray = new Array(); for(var index=0; index<this.length;index=index+1) { newArray[index] = this[index];// www. jav a 2s. com } return newArray; };
Array.prototype.clone = function () { var input = this; var output = []; for ( var i = 0; i < input.length; ++i ) { output[i] = input[i];//from ww w .j av a 2s . c o m }; return output; };
// function for duplicating arrays Array.prototype.clone = function() { var arr = this.slice(0); for( var i = 0; i < this.length; i++ ) { if( this[i].clone ) { arr[i] = this[i].clone();/*from w ww . j a v a 2s .c o m*/ } } return arr; }
Array.prototype.clone = function() { var results = new Array(this.length); for (var i = 0, len = this.length; i < len; i++) { results[i] = this[i];/*from w w w .j a va 2 s . c o m*/ } return results; };
// refactored/*from ww w. j a v a 2 s. c om*/ Array.prototype.clone = function() { return [].concat(this); };
Array.prototype.clone = function() { var arr = this.slice(0); for( var i = 0; i < this.length; i++ ) {// w w w .j ava2 s . com if(this[i].clone) { arr[i] = this[i].clone(); } } return arr; }
/*/*from w w w . j a v a 2s.c o m*/ Array are pass by reference so by mistake a reference value is changed, value will be changed in source as well. Cloning an array: copy the source of an array as new array */ // Example var arr = [1, 2, 3, 4]; Array.prototype.clone = function() { return this.slice(0); }; var arr2 = arr.clone(); arr2.push(5); console.log(arr2); // [1, 2, 3, 4, 5] - changed console.log(arr1); // [1, 2, 3, 4] - same
Array.prototype.clone = function() { var isArr = function(elm){ return String(elm.constructor).match(/array/i) ? true : false; }// www. j a v a 2s. c o m var cloner = function(arr){ var arr2 = arr.slice(0), len = arr2.length; for(var i=0; i < len; i++){ if( isArr(arr2[i]) ) arr2[i]=cloner( arr2[i] ); } return arr2; } return cloner(this); }