本文介绍了对多维数组javascript中的所有整数求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我有这个:

function arrSum(){
  *code here*
}

如何编写arrSum函数,使其可以对多维数组(可变深度)中的所有整数求和.

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

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.

推荐答案

只需使用递归即可编写这样的函数

Simply you can write a function like this with recursion

function arrSum(arr) {
  var sum = 0;
  // iterate array using forEach, better to use for loop since it have higher performance
  arr.forEach(function(v) {
    // checking array element is an array
    if (typeof v == 'object')
      // if array then getting sum it's element (recursion)
      sum += arrSum(v);
    else
      // else adding the value with sum
      sum += v
  })
  // returning the result
  return sum;
}

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

使用for循环

function arrSum(arr) {
  var sum = 0;
  for (var i = 0; i < arr.length; i++) {
    if (typeof arr[i] == 'object')
      sum += arrSum(arr[i]);
    else
      sum += arr[i];
  }
  return sum;
}

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

这篇关于对多维数组javascript中的所有整数求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 16:32