发现嵌套阵列的总和 [英] Finding the sum of a nested array

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

问题描述

我试图找到一个嵌套数组的所有号码的总和,但我不让它正常工作。这是我尝试:

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,我不知道为什么。

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

推荐答案

与code中的问题是, 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 A 的声明,使他们本地的功能:

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天全站免登陆