如何对表示整数的字符串数组进行求和

3

如何对这样的数组求和:

[ '', '4490449', '2478', '1280990', '22296892', '244676', '1249', '13089', '0', '0', '0\n' ]

如果我在该数组上调用类似于 ['','4490449', ... , '0\n' ].reduce(function(t,s){ return t+s) 的方法,那么字符串会被连接而不是相加。

我尝试使用 parseInt() 进行一些类型转换,但结果为 NaN :)


“''”并不真正代表一个整数;你期望它如何处理? - ruakh
我是指“?”可以代表零或者什么? - zzeroo
6个回答

9

您需要确保正在求和的值为整数。以下是一个可能的解决方案:

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
我认为你应该从正则表达式中删除 $parseInt 忽略尾随的非数字字符(例如 '32a' 变成了 32),而 OP 的示例包括 '0\n' 作为一个元素。(当然,你的版本将把 '0\n' 转换为 0,但这主要是巧合。) - ruakh
虽然您所说的是正确的,但我认为期望的是字符串应该表示数值整数,而 0\n 并不是。 - Rob Raisch

4

这似乎可以正常工作:

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

这也允许添加小数。 - Shmiddty
这个函数中前置的 || 0 是什么意思? - Rob DePietro

2

试试这个:

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

在这里点此使用Fiddle。


1

你在使用parseInt方面是正确的。

但你需要对每个reduce参数都使用它。

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

Mozilla的ECMAscript 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/

0

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

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

不,这是我之前尝试过的方法。... function(t, s) { ..... return parseInt(t) + parseInt(s); ..... } ... ); NaN - zzeroo
在代码之前读取:“您的数组中有一些不是整数的值”。 '' 不是整数,'0\n' 也不是。 - Dominic Goulet

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;
  }
}

请不要仅仅发布代码作为答案,还要提供解释您的代码是如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同。 - Tyler2P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接