JS如何求和/平均?

时间:2017-01-12 00:29:30

标签: javascript

我有一个对象,需要对每个动态范围求和/平均值。但似乎无法将这些转化为数字。请帮助。

Console Log
Code Sample

Expand/Collapse Created : 1/3/2017 ‎<span>(10)‎</span>
Expand/Collapse Created : 1/4/2017 ‎<span>(38)‎</span>
Expand/Collapse Created : 1/5/2017 ‎‎<span>(13)</span>
Expand/Collapse Created : 1/6/2017 ‎‎<span>(35)</span>
Expand/Collapse Created : 1/9/2017 ‎‎<span>(46)</span>
Expand/Collapse Created : 1/10/2017 ‎‎<span>(17)</span>
Expand/Collapse Created : 1/11/2017 ‎‎<span>(27)</span>


var arr = [];
    $(".ms-gb span").each(function(index, elem){
        arr.push($(this).text());
    });

    $("#result").text(arr.join("+"));  // (10)+‎(38)+‎(13)+‎(35)+‎(46)+‎(17)+‎(27)

var allNumbers =   document.getElementById('result').innerText; // (10)+‎(38)+‎(13)+‎(35)+‎(46)+‎(17)+‎(27)
    allNumbers = allNumbers.replace(/["'()]/g,""); // ‎‎10+‎38+‎13+‎35+‎46+‎17+‎28
var newString  = allNumbers.split("+");  // Object - ["‎10", "‎38", "‎13", "‎35", "‎46", "‎17", "‎27"]

3 个答案:

答案 0 :(得分:1)

你好,非常接近。我建议使用reduce功能

var sum = allNumbers.reduce(function(a,b){ return +a + +b; }, 0)
在a和b前面的plus signs可能看起来很奇怪,但它是一种在javascript中将字符串强制转换为数字的快速方法

答案 1 :(得分:0)

您必须迭代数组,然后将每个字符串更改为数字。之后,您可以将每个元素添加到自身。

var a = 0;
for(var i=0;i<newString.length;i++) {
    a += parseInt(newString[i]);}

然后a将是总和

答案 2 :(得分:0)

您可以删除非数字字符,解析每个数字,然后在循环中执行添加。

&#13;
&#13;
// variables
var sum = 0;
var average = 0;
var numOfSpan = $('span').length;

// each span loop
$('span').each(function(key, val){
  // add the value of the span to the sum var
  sum+= parseInt($(this).text().replace(/\D/g,''));  
  
  // on the last itteration ...
  if(key == (numOfSpan - 1)) {
    
    // calulate average
    average = sum / numOfSpan;
    
    // log sum and average
    console.log('sum = ' + sum);
    console.log('average = ' + average);
  }
});
&#13;
<span>(10)</span>
‎<span>(38)</span>
<span>(13)</span>
<span>(35)</span>
‎<span>(46)</span>
‎‎<span>(17)</span>
<span>(27)</span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;