如何将所有 mybag
数组值添加到 total_w
中,其中 mybag
具有 float
或的混合值int
?
var mybag = [];
mybag[0] = 20.50;
mybag[1] = 10.13;
mybag[3] = 0;
//so total_w should be 30.63 not: 20.5010.13
var total_w = 0;
var comma = '';
for (key in mybag) {
active_mybag = active_mybag + comma + parseFloat(mybag[key]).toFixed(2);
total_w = Math.round(total_w + parseFloat(mybag[key]).toFixed(2));
comma = ",";
}
console.log('> ', total_w, active_mybag);
最佳答案
您的代码存在许多问题,因此这里不是一串注释而是答案。
var mybag = [ /* bunch of values */];
var total = +mybag.reduce((a, b) => a + +b, 0).toFixed(2);
适用于数字或数字字符串。 Fiddle 。分割如下:
减少从0开始。
“a”参数是累加器。
“b”参数是该迭代的数组值。
b 通过一元加运算符转换为数字
b 添加到 a 并返回
总和被缩减为 2 位精度的数字字符串
通过前面的加号将其转换回数字
关于javascript - 如何添加 float 和非 float ,其他?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37312066/