function ConwayNeighbours(a) {
var b = a.slice()
for(i=0; i<a.length; i++)
for(j=0; j<a[i].length; j++){
if(a[i][j+1])
b[i][j]++
if(a[i][j-1])
b[i][j]++
if(a[i-1]){
if(a[i-1][j])
b[i][j]++
if(a[i-1][j+1])
b[i][j]++
if(a[i-1][j-1])
b[i][j]++
}
if(a[i+1]){
if(a[i+1][j])
b[i][j]++
if(a[i+1][j+1])
b[i][j]++
if(a[i+1][j-1])
b[i][j]++
}
console.log("i",i,"j",j,"a",a,"b",b)
}
return b
}
ConwayNeighbours([[false,true], [true,true]])
我的问题是数组 a
为何以及如何发生变化,我没有做任何影响,我确保通过 slice 克隆它从原始数组返回一个新数组,有人可以解释一下
最佳答案
Slice 返回一个数组的浅拷贝,所以如果你有一个数组数组,数组引用将按原样复制。根据数据成员的类型,执行数组深层复制的一种快捷方式是执行以下操作而不是 b=a.slice()
:
var b = JSON.parse(JSON.stringify(a));
或者,您可以使用递归数组深度克隆函数,例如这个 by Andrew Ray :
function arrayClone( arr ) {
var i, copy;
if( Array.isArray( arr ) ) {
copy = arr.slice( 0 );
for( i = 0; i < copy.length; i++ ) {
copy[ i ] = arrayClone( copy[ i ] );
}
return copy;
} else if( typeof arr === 'object' ) {
throw 'Cannot clone array containing an object!';
} else {
return arr;
}
}
关于javascript - 通过 Array.prototype.slice() 更改克隆数组会影响原始数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35002640/