javascript - 通过 Array.prototype.slice() 更改克隆数组会影响原始数组

标签 javascript arrays

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/

相关文章:

javascript - 哈希表与 JavaScript 中的对象

javascript - 在没有 id 的标签内重命名类

javascript - 一个 .mjs 文件,可在浏览器和 NodeJS 上使用 native JS 模块

java - 在 Java 中查找第三大 no

javascript - 无法将数据库中的数据与字符串数组进行比较

C++ - 以特定方式输入字符串

javascript - 正则表达式将算术表达式分成几部分

javascript - 自定义 block JavaScript?

php - json 解码 - 从对象获取单个数组?

java - 字符串数组的元素无法与字符串进行比较