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

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

问题描述

我想和我的朋友玩得开心,他解决了 8m 7s 中提到的问题,对我来说已经过去了 20m.我不知道如何在 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)

我写的代码是:

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.

任何想法将不胜感激.也尽量在 8m 7s 之前完成,我的哥们完成了.

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

推荐答案

if (i[a] instanceof Array) { 部分的内部,你必须使用递归来操作嵌套具有相同 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天全站免登陆