我有以下一段代码,可以将多个字符串转换为数字,效果很好,但我不喜欢它的外观,想知道是否可以用更好的方式编写它。
Number(result.channels.electricity.chan[0].day[0]._)
+ Number(result.channels.electricity.chan[1].day[0]._)
+ Number(result.channels.electricity.chan[2].day[0]._)
+ Number(result.channels.electricity.chan[3].day[0]._)
+ Number(result.channels.electricity.chan[4].day[0]._)
+ Number(result.channels.electricity.chan[5].day[0]._)
有没有更简洁的写法?
最佳答案
使用reduce非常简单:
var sum = results.channels.electricity.chan.reduce(function(a, b){
return a + Number(b.day[0]._);
}, 0);
关于javascript - 在 Javascript 中将多个字符串添加为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34967122/