在 JS 函数中使用递归的奇怪循环 [英] Weird loop using recursion in JS function

查看:38
本文介绍了在 JS 函数中使用递归的奇怪循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对嵌套数组中的元素求和.例如 arraySum([1,[2,3],5,[[4]]]) 应该返回 15

I am trying to sum the elements inside a nested array. For example arraySum([1,[2,3],5,[[4]]]) should return 15

一切似乎都很好,除非我尝试 return array.pop() + arraySum(array) 进入一个奇怪的无限循环.

Everything seems ok except when I try to return array.pop() + arraySum(array) it goes into a weird infinite loop.

一切顺利,直到代码到达那个代码.我尝试返回数组的值,但我看不出任何问题.

Everything goes well until code reaches that code. I tried to return the value of the array and I see no problems at all.

谁能告诉我我的代码有什么问题?

Can anyone tell me what's wrong with my code?

var arraySum = function(array) {
  
  if(array.length === 0){
      return 0
    }
  if(Array.isArray(array[array.length - 1])){
    var x = array[array.length - 1].reduce((accumulator, currentValue) => accumulator + currentValue);

    array.pop()
    array.push(x)
    return arraySum(array)

    }       

  return  array.pop() + arraySum(array)
};

console.log(arraySum([1,[2,3],5,[[4]]]))

推荐答案

在这里,一些丰盛的递归解决了我们的问题.问题是您在迭代数组时对其进行了变异,特别是将项目推回其中.实际上,您永远不应该这样做.

Some hearty recursion solves our problem here. The issue was that you were mutating the array while iterating over it, specifically pushing items back into it. In practice you should never do this.

    function arraySum(array) {
      if (array.length === 0) {
        return 0;
      }
      return array.reduce((previous, current) => {
        if (Array.isArray(current)) {
          return previous + arraySum(current);
        }
        return previous + current;
      }, 0);
    }

    console.log(arraySum([1, [2, 3], 5, [[4]]]));

这篇关于在 JS 函数中使用递归的奇怪循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆