简体   繁体   中英

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

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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