Javascript的无限嵌套数组处理 [英] Javascript unlimited nested array handling

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

问题描述

我想好好陪陪我的朋友谁解决了8米7S提到的问题,对我来说已经是20米了。我无法弄清楚如何处理无限嵌套数组中的JavaScript。

I am trying to have fun with my buddy who solved the problem mentioned in 8m 7s, and for me it is already 20m gone. I can't figure out how to handle unlimited nested array in javascript.

问题是这样的:

// i will be an array, containing integers, strings and/or arrays like itself.
// Sum all the integers you find, anywhere in the nest of arrays.

于是

arraySum([[1,2,false],'4','5']) will return 3 (passed)
arraySum([[1,2,3],4,5]) will return 15 (passed)
arraySum([[[[[[[[[1]]]]]]]], 1]) will return 2 (failed)

在code我写的是:

The code I wrote is:

function arraySum(i) {

sum = 0;
tmp =0;
for (var a=0; a<i.length; a++){
    if (i[a] instanceof Array) {
        ar = i[a];
        for (var j=0; j<ar.length; j++){
            tmp +=ar[j];
        }
    }
    if (typeof i[a] == "number")
        sum += i[a];
        console.log(sum);
}
return sum + tmp;

}

正如你可以看到它不处理,我没有过去的情况,因为我无法弄清楚如何处理无限窝在JS。

As you can see it does not handle the last situation that I failed as I can't figure out how to handle unlimited nest in JS.

任何想法会更加AP preciated。 也可以尝试之前8米7S,在我的朋友完成完成它。

Any idea will be much appreciated. Also try to finish it before 8m 7s, which my buddy finished in.

推荐答案

里面的如果(I [A]的instanceof阵列){的一部分,你必须使用递归嵌套阵列相同的 arraySum 功能操作,而不仅仅是用另一个循环。试试这个:

Inside of the if (i[a] instanceof Array) { part, you'll have to use recursion to operate on nested arrays with the same arraySum function, not just use another loop. Try this:

var arraySum = (function () {
    "use strict";

    var sumFunc, isArray;

    sumFunc = function (arr) {
        var sum, i, j, cur, toAdd;

        sum = 0;

        for (i = 0, j = arr.length; i < j; i++) {
            cur = arr[i];

            toAdd = 0;
            if (isArray(cur)) {
                toAdd = sumFunc(cur);
            } else if (typeof cur === "number") {
                toAdd = cur;
            }

            sum += toAdd;
        }

        return sum;
    };

    isArray = Array.isArray || function (obj) {
        return Object.prototype.toString.call(obj) === "[object Array]";
    };

    return sumFunc;
}());

演示: http://jsfiddle.net/Q7JPM/1

该函数只是遍历数组中的所有项目,并返回里面发现的任何数字的总和。如果项目本身就是一个数组,它会调用 arraySum 并将该数组......加上结果的总和。如果它是一个数字,它只是增加了,为的总和。

The function just loops through all items in an array, and returns the sum of any numbers found inside. If the item is an array itself, it calls arraySum and passes that array...adding the result to the sum. If it's a number, it simply adds that to the sum.

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

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