【发布时间】: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