【问题标题】:Issue while making a copy of 2D Array制作二维数组副本时出现问题
【发布时间】:2020-08-17 03:06:49
【问题描述】:

我的目标是为 2D 数组找到“N”。 'N' = 角元素的总和 * 非角元素的总和。 对于“N”计算,我将字符串和布尔元素分别更改为它们的 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”,而不改变原始数组。因为所有计算都是在临时数组上完成的。但事实并非如此。

【问题讨论】:

    标签: javascript arrays 2d deep-copy shallow-copy


    【解决方案1】:

    您的问题是因为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, 2], [3, 4]];
    let temp = [...arr.map(a => [...a])];
    temp[0][1] = 6;
    console.log(arr);
    console.log(temp);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 2014-12-06
      • 2014-05-02
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多