复制2D阵列时出现问题

问题描述

在这里的目标是为2D阵列找到'N'。 'N'=拐角元素之和*非拐角元素之和。 对于“ N”计算,我将String和Boolean元素分别更改为其ASCII,1或0。但是我的原始数组在此过程中发生了变化。 不明白为什么?

 function findN(arr) {
    var temp = [...arr]
    // first we change all elements to numbers
    for (let i = 0; i < temp.length; i++) {
        for (let j = 0; j < temp.length; j++) {
            if (typeof temp[i][j] == 'string') {
                temp[i][j] = temp[i][j].charCodeAt()
            } else if (temp[i][j] == true) {
                temp[i][j] = 1
            } else if (temp[i][j] == false) {
                temp[i][j] = 0
            }
        }
    }



    // N calculation starts here
    let r = temp.length // rows
    let c = temp[0].length // columns

    var corner_Sum =
        temp[0][0] + temp[0][c - 1] + temp[r - 1][0] + temp[r - 1][c - 1]

    var total_Sum = 0
    for (let i = 0; i < temp.length; i++) {
        for (let j = 0; j < temp.length; j++) {
            total_Sum = total_Sum + arr[i][j]
        }
    }

    var N = corner_Sum * (total_Sum - corner_Sum)

    return N
}

findN()到此结束。它应返回“ N”,而不更改原始数组。由于所有计算都是在临时数组上完成的。但是事实并非如此。

解决方法

您的问题是因为arr是一个数组数组;当您使用

复制它时
temp = [...arr]

temp成为对arr中相同子数组的引用的数组。因此,当您更改temp中的值时,它也会更改arr中的相应值。您可以在一个简单的示例中看到它:

let arr = [[1,2],[3,4]];
let temp = [...arr];
temp[0][1] = 6;
console.log(arr);
console.log(temp);

要解决此问题,请使用诸如herehere中所述的深层副本。例如,如果arr最多为二维,则可以嵌套扩展运算符:

let arr = [[1,4]];
let temp = [...arr.map(a => [...a])];
temp[0][1] = 6;
console.log(arr);
console.log(temp);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...