Recursion - Sum Nested Array

前端 未结 7 1552
一向
一向 2021-01-03 12:24

I\'m trying to sum a nested array [1,2,[3,4],[],[5]] without using loops but I don\'t see what\'s wrong with what I have so far.

function sumItem         


        
7条回答
  •  迷失自我
    2021-01-03 13:15

    This is similar to some of the other solutions but might be easier for some to read:

     function Sum(arr) {
       if (!arr.length) return 0;
       if (Array.isArray(arr[0])) return Sum(arr[0]) + Sum(arr.slice(1));
       return arr[0] + Sum(arr.slice(1));
     }
    
     console.log(Sum([[1],2,[3,[4,[5,[6,[7,[8,9,10],11,[12]]]]]]])) // 78
    

提交回复
热议问题