Sum all integers in a multidimensional array javas

2019-02-18 06:30发布

Let's say I have this:

function arrSum(){
  *code here*
}

How do I write the arrSum function such that it can sum all the integers within a multidimensional array (of variable depth).

I.e.

arrSum([2, 5, [4, 6], 5]) === 22;

I know there must be an answer to this somewhere but I really can't find it. If this is a duplicate please let me know.

7条回答
太酷不给撩
2楼-- · 2019-02-18 07:17

Check this:

function arrSum(objArr){
  var total = 0;
  for(var outerLoop=0; outerLoop < objArr.length; outerLoop++){
    if(objArr[outerLoop].constructor === Array){
      for(var innerLoop=0; innerLoop < objArr[outerLoop].length; innerLoop++){
        total += objArr[outerLoop][innerLoop];
      }
    } else {
      total += objArr[outerLoop];
    }
  }
  return total;
}

alert (arrSum([2, 5, [4, 6], 5]));
查看更多
登录 后发表回答