简体   繁体   English

JS如何求和/求平均值?

[英]JS how to Sum/Average?

I have an object and need to sum/average of each dynamic span.我有一个对象,需要对每个动态跨度求和/求平均值。 Can't seem to convert those to numbers though.虽然似乎无法将它们转换为数字。 Please Help.请帮忙。

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"]

well you're pretty close.嗯,你很接近。 i'd recommend using the reduce function我建议使用reduce函数

var sum = allNumbers.reduce(function(a,b){ return +a + +b; }, 0)

the plus signs in front of a and b might look weird, but its a quick way to coerce a string into a number in javascript a 和 b 前面的加号可能看起来很奇怪,但它是一种在 javascript 中将字符串强制转换为数字的快速方法

You have to iterate your array and then change every string to number.您必须迭代数组,然后将每个字符串更改为数字。 After that you can add every elements to itself.之后,您可以将每个元素添加到自身。

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

And then a will be the sum然后a将是总和

You can strip out non-numeric characters, parse each number, and then perform the addition within the loop.您可以去除非数字字符,解析每个数字,然后在循环内执行加法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM