查找嵌套数组的总和 [英] Finding the sum of a nested array

查看:23
本文介绍了查找嵌套数组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个嵌套数组的所有数字的总和,但我没有让它正常工作.这是我尝试过的:

I tried finding the sum of all numbers of a nested array, but I don't get it to work correctly. This is what I tried:

function arraySum(i) {
  sum = 0;
  for (a = 0; a < i.length; a++) {
    if (typeof i[a] == 'number') {
      sum += i[a];
    } else if (i[a] instanceof Array) {
      sum += arraySum(i[a]);
    }
  }
  return sum;
}

当您尝试使用数组 [[1,2,3],4,5] 时,它会得到 6 作为答案,而不是 15.有人知道哪里有错吗?

When you try it out with the array [[1,2,3],4,5], it gets 6 as the answer, instead of 15. Does somebody know where there is a mistake in it?

推荐答案

你的代码的问题是 suma 变量是全局的,而不是局部的.因此,您会得到一个无限循环(函数中第一个条目的 a 被第二个条目重置,因此再次处理相同的元素).

The problem with your code is that the sum and a variables are global, instead of local. Because of this you get an infinite loop (a from the first entry in the function is reset by the second entry, so the same elements are processed again).

通过将 var 添加到声明 suma 的位置来修复它,以使它们成为函数的局部变量:

Fix it by adding var to where sum and a are declared to make them local to the function:

function arraySum(i) {
    var sum=0; // missing var added
    for(var a=0;a<i.length;a++){ // missing var added
        if(typeof i[a]=="number"){
            sum+=i[a];
        }else if(i[a] instanceof Array){
            sum+=arraySum(i[a]);
        }
    }
    return sum;
}

演示:http://jsbin.com/eGaFOLA/2/edit

这篇关于查找嵌套数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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