Here's a generic solution, which will work for any depth, and assumes that your Arrays are actually Arrays, and not Array-like objects.
function clone(arr) {
arr = arr.slice()
for (var i = 0; i < arr.length; i++)
if (Array.isArray(arr[i]))
arr[i] = clone(arr[i])
return arr
}
The Array.isArray
method can be shimmed if needed for older browsers.
if (!Array.isArray) {
Array.isArray = function(arr) {
return Object.prototype.toString.call(arr) === "[object Array]"
}
}
function clone(arr) {
return arr.map(function(item) {
if (Array.isArray(item))
return clone(item)
return item
})
}
Here's a solution that uses .map()
instead.