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

标签 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)那个数组,字符串是连接在一起的,而不是相加的。

我已经尝试使用 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/

相关文章:

javascript - 在提交调用 webapi 之前获取 Angularjs 变量中的输入值

javascript - 如何在开发和生产中添加不同的 Javascript

javascript - 依次执行 Promise.all

PHP魔术方法__get和[]使值消失

arrays - 从重复范围创建函数

node.js - sequelize.js belongsToMany 在非主键上

node.js - 如何使用 next 在 AWS S3 上托管静态文件?

javascript - 为什么 $timeout 在不同的 Controller 中调用 $scope 函数?

javascript - 类似数组/映射的数据结构,具有对项目的唯一 ID 支持、O(1) get() 方法且无重复

Javascript数组有数据但长度为零