如何添加浮动和非浮动,其他

How to add float and non-float, others?

本文关键字:其他 何添加 添加      更新时间:2023-09-26

如果mybag具有floatint的混合值,如何将所有mybag数组值添加到total_w中?

  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);

将使用数字或数字字符串。不停摆弄下面是一个分解:

reduce从0开始。

"a"参数是累加器。

"b"参数是该迭代的数组值。

b由一元加运算符转换为数字

b被添加到a并返回

总和被缩减为2位精度的数字字符串

通过前面处的加号将其转换回数字

  var active_mybag = [];  
  var total_w = mybag.reduce(function(acc,e){
    // Value of array to float
    e = parseFloat(e);
    // Collect text representations of rounded value
    active_mybag.push( e.toFixed(2) );
    // Subtotal
    return acc + e;
  },0 ).toFixed(2); // Convert sum to string representation
  active_mybag = active_mybag.join(',');

[https://jsfiddle.net/ot1p37mv/]