I want to make a clone of multidimensional Array so that i can play arround with the clone array without affecting main Array.
I found that this approach is better than meouw's :
var source = [
[1, 2, {c:1}],
[3, 4, [5, 'a']]
];
// Create a new method ontop of the "Array" primitive prototype:
Array.prototype.clone = function() {
function isArr(elm) {
return String(elm.constructor).match(/array/i) ? true : false;
}
function cloner(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);
}
// Clone
var copy = source.clone();
// modify copy
copy[0][0] = 999;
console.dir(source);
console.dir('**************');
console.dir(copy);
String
, Numbers
, Objects
) :var source = [
[1,2, {a:1}],
["a", "b", ["c", 1]]
];
// clone "srouce" Array
var copy = JSON.parse(JSON.stringify(source));
// modyfy clone
copy[0][0] = 999;
// print both arrays
console.dir(copy)
console.log('***********')
console.dir(source)