如何对这样的数组求和
[ '',
'4490449',
'2478',
'1280990',
'22296892',
'244676',
'1249',
'13089',
'0',
'0',
'0\n']
如果我在 ['','4490449', ... , '0\n' ].reduce(function(t,s){ return t+s)
那个数组,字符串是连接在一起的,而不是相加的。
我已经尝试使用 parseInt()
进行一些转换,但这会导致 NaN
:)
最佳答案
您需要确保求和的值是整数。这是一种可能的解决方案:
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/ 处的 fiddle
关于javascript - 如何对表示整数的字符串数组求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13128610/