【问题标题】:How to sum an array of number which contains string in js?如何在js中对包含字符串的数字数组求和?
【发布时间】:2020-10-11 13:54:11
【问题描述】:

我的数组:

const a = [                                       
  {                                               
    "baseFare": "1439.00",                                       
  },  
  {                                               
    "baseFare": "1739.00",                                       
  },    
  {                                               
    "baseFare": "1039.00",                                       
  },                                    
]                                             

注意:const a 中值的数量会增加或减少用户的决定!数组中可能有 1 个或 5 个或 7 个值!

如何对所有值求和并输出一个值,在某些情况下,如果它只有一个值,那么输出应该是直接的单个值!

如何做到这一点?

我的代码:

a.reduce((a, b) => a + b, 0)

【问题讨论】:

  • 你可以先映射吗? a.map(({ baseFare }) => baseFare).reduce(...

标签: javascript arrays reactjs


【解决方案1】:

你快到了 试试这个,

a.reduce((a, b) => a + (+b.baseFare), 0);

//a is the accumulator , and it start with 0 its an integer
//If you need to access baseFare, then you have to get it from object b.baseFare,
//b.baseFare is a string so you have to convert it to a number (+b.baseFare) is for that

如果您确实需要将其作为浮点数获取,例如:5000,显示为“5000.00”然后尝试一下

let sum = a.reduce((a, b) => a + (+b.baseFare), 0);;
sum = sum.toFixed(2); //"4217.00"

【讨论】:

  • 像魅力一样工作,因为数字是浮点数,如何对所有浮点值求和?
  • 它也会保留浮点数,如果你输入1439.55,那么你会看到输出是一个浮点数
【解决方案2】:

只需循环,将字符串转换为数字:

let result = 0;
for (const entry of a) {
    result += +entry.baseFare;
}

或者解构:

let result = 0;
for (const {baseFare} of a) {
//         ^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−− destructuring
    result += +baseFare;
}

一元 + 只是从字符串转换为数字的一种方法。我会在this other answer 中查看您的所有选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多