您的代码在一维数组上工作得很好:
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);
输出:
"调用前" [2, 3, 1, 5, 2, 3, 7, 2] "在函数中,更改前" [2, 3, 1, 5, 2, 3, 7, 2] "在函数中, 之后更改” [2, 17, 1, 5, 2, 3, 7, 2] “通话后” [2, 3, 1, 5, 2, 3, 7, 2]
事实上,它是一个 2D 阵列正在吸引你。查看克隆 2D javascript 数组的堆栈溢出响应:
使用 javascript 进行多维数组克隆
现在使用此代码:
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);
输出:
"调用前" [[2, 3], [1, 5, 2], [3, 7, 2]] "在函数中,更改前" [[2, 3], [1, 5, 2], [ 3, 7, 2]] "in func, after change" [[2, 3], [1, 2], [3, 7, 2]] "调用后" [[2, 3], [1, 5 , 2], [3, 7, 2]]