Your code works just fine on a 1 dimensional array:
function c(a) {
var l = a.slice(0);
console.log('in func, before change',l);
l[1] = 17;
console.log('in func, after change',l);
}
var a = [2,3,1,5,2,3,7,2];
console.log('before call', a);
c(a);
console.log('after call',a);
Output:
"before call"
[2, 3, 1, 5, 2, 3, 7, 2]
"in func, before change"
[2, 3, 1, 5, 2, 3, 7, 2]
"in func, after change"
[2, 17, 1, 5, 2, 3, 7, 2]
"after call"
[2, 3, 1, 5, 2, 3, 7, 2]
It's the fact that it is a 2D array is hosing you. Check out this stack overflow response on cloning 2D javascript arrays:
Multidimensional Array cloning using javascript
Now using this code:
Array.prototype.clone = function() {
var arr = this.slice(0);
for( var i = 0; i < this.length; i++ ) {
if( this[i].clone ) {
//recursion
arr[i] = this[i].clone();
}
}
return arr;
}
function c(a) {
var l = a.clone();
console.log('in func, before change',l);
l[1].splice(1,1);
console.log('in func, after change',l);
}
var a = [[2,3],[1,5,2],[3,7,2]];
console.log('before call', a);
c(a);
console.log('after call',a);
Output:
"before call"
[[2, 3], [1, 5, 2], [3, 7, 2]]
"in func, before change"
[[2, 3], [1, 5, 2], [3, 7, 2]]
"in func, after change"
[[2, 3], [1, 2], [3, 7, 2]]
"after call"
[[2, 3], [1, 5, 2], [3, 7, 2]]