递归求和二维数组

时间:2019-03-05 19:57:46

标签: javascript arrays recursion dimensional

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

1 个答案:

答案 0 :(得分: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))