您的代码在一维数组上运行良好:
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]
“在 func 中,在更改之前”
[2、3、1、5、2、3、7、2]
“在 func 中,更改后”
[2, 17, 1, 5, 2, 3, 7, 2]
“通话后”
[2, 3, 1, 5, 2, 3, 7, 2]
事实上,它是一个 2D 阵列正在吸引您。查看克隆 2D javascript 数组的堆栈溢出响应:
Multidimensional Array cloning using 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]]
“在 func 中,在更改之前”
[[2, 3], [1, 5, 2], [3, 7, 2]]
“在 func 中,更改后”
[[2, 3], [1, 2], [3, 7, 2]]
“通话后”
[[2, 3], [1, 5, 2], [3, 7, 2]]