Javascript - 字符串小数的总和

时间:2018-04-06 11:50:37

标签: javascript arrays loops iteration decimal

我有和小数组的字符串数组。我需要迭代数组并得到它们的总和。例如

function check() {
    let arr = ["1,50", "1,50"];
    let sum1 = 0;
    let sum2 = "0";
    let sum3 = 0

    for (let i = 0, length = arr.length; i < length; i++) {
       sum1 += +arr[i];
       sum2 += +arr[i];
       sum3 +=  arr[i];  

    }
    console.log(sum1, sum2, sum3)
    //sum1 = NaN
    //sum2 = '0NaNNaN'
    //sum3 = 01,501,50
}

总和应为3或3,00。

1 个答案:

答案 0 :(得分:2)

您可以使用reduce()作为总和,replace(),替换为.

&#13;
&#13;
let arr = ["1,50", "1,50"];
const result = arr.reduce((r, e) => r + +e.replace(',', '.'), 0)
console.log(result)
&#13;
&#13;
&#13;