function twoDSum(arr){
debugger
result = 0
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result += twoDSum(arr[i])
} else {
result += arr[i]
}
}
return result
}
array_1 = [
[4, 5],
[1, 3, 7, 1]
]
console.log(twoDSum(array_1))
上面的代码正常工作。但是,我的问题是为什么下面的代码会产生错误的答案。我假设我正在计算子阵列的总和并将其存储到变量中,然后将其添加到我的结果中,它在每个数组中都在加倍
function twoDSum(arr){
debugger
result = 0
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
let subSum = twoDSum(arr[i])
result += subSum
} else {
result += arr[i]
}
}
return result
}
array_1 = [
[4, 5],
[1, 3, 7, 1]
]
console.log(twoDSum(array_1))
使用本地result
变量而不是全局:
function twoDSum(arr){
debugger
let result = 0
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
let subSum = twoDSum(arr[i])
result += subSum
} else {
result += arr[i]
}
}
return result
}
array_1 = [
[4, 5],
[1, 3, 7, 1]
]
console.log(twoDSum(array_1))