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

Javascript 如何对表示整数的字符串数组求和,javascript,arrays,node.js,casting,Javascript,Arrays,Node.js,Casting,如何对这样的数组求和 [ '', '4490449', '2478', '1280990', '22296892', '244676', '1249', '13089', '0', '0', “0\n'] 如果我在该数组上调用类似于['','4490449',…,'0\n'].reduce(函数(t,s){return t+s),则stings是连接的,而不是求和的 我尝试了使用parseInt()进行强制转换,但结果是NaN:)数组中有些值不是整数。假设它们都是整数,则可以执行以下操作:

如何对这样的数组求和

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

如果我在该数组上调用类似于
['','4490449',…,'0\n'].reduce(函数(t,s){return t+s)
,则stings是连接的,而不是求和的


我尝试了使用
parseInt()
进行强制转换,但结果是
NaN
:)

数组中有些值不是整数。假设它们都是整数,则可以执行以下操作:

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

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

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”打印到控制台


请参见位于

的小提琴,这似乎可以正常工作:

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
试试这个:

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

您使用parseInt是正确的

但是您需要对每个reduce参数使用它

此外,您还需要检查每个parseInt的结果是否是一个数字,因为如果不是,函数将尝试将一个数字与NaN求和,而所有其他求和结果也将是NaN

Mozilla的ECMAscript说:

如果第一个字符无法转换为数字,请使用parseInt 南返回

然后,为了避免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)​​​);​
这里有一个JSFIDLE,它可以工作:

import java.util.List;
公共类混合总和{
/*
*假设输入仅为整数o字符串类型
*/
公共整数和(列表混合){
//一个新数组,用于在将所有元素转换为整数后存储混合列表中的所有元素
int[]newIntList=newint[mixed.size()];
//变量来存储新数组中所有元素的总和
整数和=0;
//循环遍历混合列表,将所有整数转换为字符串,然后再转换回字符串
//(mixed.get(i)+“”)将所有整数转换为字符串,并将字符串保留为字符串
//函数的作用是:将所有内容转换回整数
对于(int i=0;i
实际上并不表示整数;您希望如何处理它?我的意思是“”可以代表零或?不,这是我以前尝试过的
[''4490449',2478',1280990',22296892',244676',1249',13089',0',0',0',0\n']NaN
在代码前面读:“数组中有一些值不是整数”。
'
不是整数,
'0\n'
也不是整数。这也允许添加小数。我认为应该从该正则表达式中删除
$
parseInt
忽略尾随的非数字(例如,
'32a'
变为
32
),OP的示例包括
'0\n'
作为一个元素。(当然,您的版本会将
'0\n'
转换为
0
,但这主要是巧合。)虽然您所说的是正确的,但我相信我们的期望是字符串应该表示数值整数值,而
0\n
则不是。请不要仅将代码作为答案发布,还要解释代码的作用以及它是如何解决问题的。带有解释的答案通常更有帮助d的质量更好,并且更有可能吸引更多的选票。
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;
  }
}