Recursion - Sum Nested Array

前端 未结 7 1553
一向
一向 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:14

    try with

     function sumItems(array) {
    
      let sum = 0;
      array.forEach((item) => {
        if(Array.isArray(item)) {
         sum += sumItems(item);
        } else {
        sum += item;
        }
      })
      return sum;
    }
    

提交回复
热议问题