zze*_*roo 1 javascript arrays casting node.js
如何总结这样一个数组
[ '',
'4490449',
'2478',
'1280990',
'22296892',
'244676',
'1249',
'13089',
'0',
'0',
'0\n' ]
如果我['','4490449', ... , '0\n' ].reduce(function(t,s){ return t+s)在那个数组上调用类似的东西,那么就会加入stings而不是求和.
我尝试了一些铸造,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
})
)?;
Run Code Online (Sandbox Code Playgroud)
将'28329823'打印到控制台.
请参阅http://jsfiddle.net/hF6xv/上的小提琴