使用JavaScript在Array中总计

时间:2017-06-13 14:57:22

标签: javascript

在计算数组中的值时,我得到这个:total =“0212.16967.04”。 此示例中的正确总数为:1179.20

function calculateSum(){
  //build array of numbers
  amtArray = [];
  $('.amount').each(function (index, value) {		
    amtArray.push($(this).text()||0);
  });
  //calculate all values and return results 	
  var sum = sumArray(amtArray);
  console.log('sum ->', sum)
}
 
function sumArray(input) {
  var total = 0;
  for (idx=0; idx <= input.length-1; idx++) {
    total += input[idx];
  }
  return total;
}

calculateSum()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="amount">212.16</div>
<div class="amount">967.04</div>

应输出:1179.20

5 个答案:

答案 0 :(得分:4)

您需要使用unary plus +(或使用NumberparseFloat或任何其他需要数字的运算符)将值从字符串转换为数字,否则如果有的话操作数是一个字符串,所有部分都被视为字符串并连接。

total += +input[idx];
//       ^

答案 1 :(得分:2)

这里的错误是你连接字符串,这是一个解决方案:

var array = ["212.16", "967.04"]

function sumArray(input) {
  var total = 0;
  for (idx = 0; idx <= input.length - 1; idx++) {
    total += parseFloat(input[idx]);
  }
  return total;
}

console.log(sumArray(array));

答案 2 :(得分:0)

您正在连接字符串值,而不是添加流动的指向数字。您可以使用parseFloat()将字符串转换为float,如下所示:

function sumArray(input) {  //input = (2) ["212.16", "967.04"]
    var total = 0;
    for (idx=0; idx <= input.length-1; idx++) {
        total += parseFloat(input[idx]);    
    }
    return total;  
}

答案 3 :(得分:0)

在函数sumArray中,您可以直接返回Array.prototype.reduce()的结果并使用Number来处理数值:

function sumArray(input) {
  return input.reduce((a, b) => a + Number(b), 0);
}

console.log(sumArray(["212.16", "967.04"]));

答案 4 :(得分:0)

除了使用一元,parsefloat,Number之外,你还应该使用toPrecision来获得你在问题中指出的最后一个零

&#13;
&#13;
var val = document.getElementsByClassName('amount');

function calculateSum() {
  var total = 0;
  for (var i = 0; i < val.length; i++) {
    var value = val[i].textContent;
    total += +value;
  }
  return total.toPrecision(6);
}
val[1].insertAdjacentHTML('afterend', calculateSum());
&#13;
<div class="amount">212.16</div>
<div class="amount">967.04</div>
&#13;
&#13;
&#13;