简体   繁体   English

制作二维数组副本时出现问题

[英]Issue while making a copy of 2D Array

My target here is to find 'N' for a 2D Array.我的目标是为 2D 数组找到“N”。 'N' = sum of corner elements * sum of non corner elements. 'N' = 角元素的总和 * 非角元素的总和。 For 'N' calculation I change String & Boolean elements to their ASCII, 1 or 0 respectively.对于“N”计算,我将 String 和 Boolean 元素分别更改为它们的 ASCII、1 或 0。 But my original array gets altered in this process.但是我原来的数组在这个过程中被改变了。 Can't understand why?不明白为什么?

 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() ends here. findN() 到此结束。 It should return 'N', without altering the original array.它应该返回“N”,而不改变原始数组。 As all calculations were done on temp array.因为所有计算都是在临时数组上完成的。 But that's not the case.但事实并非如此。

Your problem is because arr is an array of arrays;您的问题是因为arr是 arrays 的数组; when you copy it using当您使用复制它时

temp = [...arr]

temp becomes an array of references to the same subarrays in arr . temp成为对arr中相同子数组的引用数组。 Thus when you change a value in temp it changes the corresponding value in arr .因此,当您更改temp中的值时,它会更改arr中的相应值。 You can see this in a simple example:您可以在一个简单的示例中看到这一点:

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

To work around this, use a deep copy such as those describedhere or here .要解决此问题,请使用此处此处描述的深层副本。 For example, if arr is at most 2-dimensional, you can nest the spread operator:例如,如果arr至多是二维的,则可以嵌套展开运算符:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM