如何对一个字符串数组求和,代表整数

时间:2012-10-29 19:52:07

标签: javascript arrays node.js casting

如何总结这样的数组 [ '', '4490449', '2478', '1280990', '22296892', '244676', '1249', '13089', '0', '0', '0\n' ]

如果我在该数组上调用类似['','4490449', ... , '0\n' ].reduce(function(t,s){ return t+s)的内容,那么就会加入stings而不是求和。

我尝试使用parseInt()进行投射,但这导致NaN:)

6 个答案:

答案 0 :(得分:5)

您需要确保要求的值是整数。这是一个可能的解决方案:

var ary=[ '', '4490449', '2478', '1280990', '22296892', 
          '244676', '1249', '13089', '0', '0', '0\n' ];

console.log(
  ary
    .map( function(elt){ // assure the value can be converted into an integer
      return /^\d+$/.test(elt) ? parseInt(elt) : 0; 
    })
    .reduce( function(a,b){ // sum all resulting numbers
      return a+b
    })
)​;

将'28329823'打印到控制台。

请参阅http://jsfiddle.net/hF6xv/

小提琴

答案 1 :(得分:1)

这似乎工作正常:

var arry = [ 'asdf', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'ham10am' ];

var res = arry.reduce(function(prev, curr){
    return (Number(prev) || 0) + (Number(curr) || 0);
});

console.log(res); // prints 45

答案 2 :(得分:1)

试试这个:

var sum = 0,
    arr = [ '', '1', '2', '3.0','4\n', '0x10' ],
    i = arr.length;

while( i-- ) {
    // include radix otherwise last element gets interpreted as 16
    sum += parseInt( arr[i], 10 ) || 0; 
}

console.log( sum ) // sum => 10 as 3.0 and 4\n were successfully parsed

小提琴here

答案 3 :(得分:1)

使用parseInt是正确的。

但是你需要为每个reduce参数使用它。

此外,您还需要检查每个parseInt的结果是否为数字,因为如果不是,该函数将尝试将数字与NaN相加,所有其他总和也将最终为NaN。

Mozilla的ECMAscript documentation on parseInt说:

  

如果第一个字符无法转换为数字,则为parseInt   返回NaN。

然后,为了避免让NaN破坏你的目标,你可以像这样实现它:

function parseIntForSum(str) {
    var possibleInteger = parseInt(str);
    return isNaN(possibleInteger) ? 0 : possibleInteger;
}

function sum(f, s) {
    return parseIntForSum(f) + parseIntForSum(s);
}

window.alert('sum = ' + [ '', '4490449', '2478', '1280990', '22296892', '244676', '1249', '13089', '0', '0', '0\n' ].reduce(sum)​​​);​

这是一个有效的jsfiddle:http://jsfiddle.net/cLA7c/

答案 4 :(得分:0)

您的数组中有一些不是整数的值。我们假设它们都是,那么你可以这样做:

['4490449', '2478', '1280990', '22296892', '244676', '1249', '13089'].reduce( 
    function(t, s) { 
        return parseInt(t) + parseInt(s); 
    }
);

答案 5 :(得分:0)

import java.util.List;

public class MixedSum {

 /*
  * Assume input will be only of Integer o String type
  */
  public int sum(List<?> mixed) {
    
    // A new array to store all the elements in the mixed list after converting them to integers
    int[] newIntList = new int[mixed.size()];
    
    // Variable to store sum of all elements in our new array
    int sum = 0;
    
    // Loop through the mixed list and convert all integers to strings and then back to string
    //(mixed.get(i) + "") converts all integers to strings and leave strings as strings
    // parseInt() function converts everything back to integers 
    for(int i = 0; i < mixed.size(); i++){
      newIntList[i] = Integer.parseInt(mixed.get(i) + "");
    }
    
    // Loops through the array and sum up all elements
    for(int i = 0; i < newIntList.length; i++){
      sum += newIntList[i];
    }
    
    //returns sum
    return sum;
  }
}