复制二维数组时出现问题
Issue while making a copy of 2D Array
我的目标是为二维数组找到 '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() 到此结束。它应该 return '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);
要解决此问题,请使用 here or here 中描述的深度复制。例如,如果 arr
最多是二维的,则可以嵌套扩展运算符:
let arr = [[1, 2], [3, 4]];
let temp = [...arr.map(a => [...a])];
temp[0][1] = 6;
console.log(arr);
console.log(temp);
我的目标是为二维数组找到 '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() 到此结束。它应该 return '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);
要解决此问题,请使用 here or here 中描述的深度复制。例如,如果 arr
最多是二维的,则可以嵌套扩展运算符:
let arr = [[1, 2], [3, 4]];
let temp = [...arr.map(a => [...a])];
temp[0][1] = 6;
console.log(arr);
console.log(temp);