请解字符串求和问题

发布于 7 年前作者 xiayin18766 次浏览最后编辑 7 年前来自 ask

有一串字符,都是数字的,如何用比较简单的方法进行求和呢?谢谢!

如  str=“123456”,相当于要求出1+2+3+4+5+6=21。

3 回复
yongshao
yongshao1 楼6 年前

const str = ‘123456’

const arr = str.split(‘’);

const result = arr.reduce((a, b) => {

return a*1 + b*1

}, 0)

console.log(result, ‘result’)

tao93
tao932 楼6 年前

记得转成数字。。

tao24
tao243 楼5 年前

### 问题解决

```

const result = str.reduce((acc, crr) => acc + crr)

```

### 方法参考

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global\_Objects/Array/Reduce

### 建议

  • 这种非小程序问题还是去专业点的社区提问吧,比如中文的segment或英文的stackover

------ 小小的分割线 ------

  • 为什么社区不支持MD

  • 为什么社区的贴子不让转载

  • 为什么微信这么屌~~~