拉出任何给定数组中的所有数字,然后将它们全部加在一起。

时间:2015-08-23 03:55:39

标签: javascript arrays recursion integer

我试图想出一个可以接受任何类型数组的函数(包含对象,其他数组,字符串,数字,布尔等)并拉出所有数字(即使它们是字符串)然后将它们全部加在一起返回总和。

到目前为止,我试图提出一个函数,它会首先找到所有整数并将它们全部加在一起,然后再担心将代表数字的任何字符串转换为整数并添加它们:

function arraySum(array) {
  // the array could be containing integers, strings, objects and/or arrays like itself.
  // Sum all the integers you find, anywhere in the nest of arrays.
  var sum = 0
  var numArray = []

    for (i=0; i > array.length; i++) {
        if (typeOf array[i] == Number) {
            numArray.push(i);
            for (j=0; j> numArray.length; j++) {
                sum += numArray[j];
                return sum;
            };
        }
    }
}

arraySum([1,2,3,["Here is a string", "67", 67], {key: "55", value: 55}, true, 56]);

我期待sum的返回值为184

总和应返回306(一旦更新函数以将数字字符串转换为整数)

2 个答案:

答案 0 :(得分:2)

var a = [1, 2, 3, ["Here is a string", "67", 67], {key: "55", value: 55 }, true, 56];


function arraySum(obj) {
    var sum = 0;
    var num = Number(obj);

    if (typeof obj === 'boolean') {
        return 0;
    }

    if (typeof num === 'number' && !isNaN(num)) {
        return num;
    }

    if (typeof obj !== 'object') {
        return 0;
    }

    if (obj.length) {
        for (var i = 0; i < obj.length; i++) {
            sum += arraySum(obj[i]);
        }
    }
    else {
        for (var p in obj) {
            sum += arraySum(obj[p]);
        }
    }

    return sum;
}


console.log(arraySum(a));

答案 1 :(得分:1)

这是jq 1.5(https://stedolan.github.io/jq/)中的解决方案。作为jq程序,它将接受任意JSON输入。由于您的输入不是严格的JSON,因此下面显示了处理您建议的输入的方法:

# summation_walk scans for numbers or numeric strings
# everywhere except in the key names, and adds them up:
def summation_walk:
  walk( if type == "object" then .[] else . end )
  | walk( if type == "string" then tonumber?
          elif (type | . == "boolean" or . == "null") then empty
          else .
          end )
  | flatten
  | add;

[1,2,3,["Here is a string", "67", 67], {key: "55", value: 55}, true, 56]
| summation_walk

的产率:

306