1

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))

4

1 回答 1

0

使用局部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))

于 2019-03-05T20:05:14.290 回答