summing numbers stored in an array in JavaScript

2020-04-27 23:44发布

I want to sum a list of numbers stored in a JavaScript object. The object is created and updated using this code:

var myscore = $('input[name="Points1"]').val();
scorelist = JSON.parse(localStorage.getItem(playerName + 'scorelist') || '[]');
        scorelist.push(myscore);
        localStorage.setItem(playerName + 'scorelist', JSON.stringify(scorelist));
        $('div.scorecolumn', column).html("Score: <br>" + scorelist.join('<br>') + "<br>");

Basically I take whatever is in the column at the time, parse it, add myscore, stringify it, join each element with a <br> and write the list to the scorecolumn. The list of numbers is saved as an object. My goal is to sum up all the numbers in the object at any given time.

This script is inside of a function that passes in a bunch of parameters which is why some variables look undefined here.

Any help would be greatly appreciated! Thanks

UPDATE:

var nicTotalScore = nicScoreList.reduce(function(score, total) {
        return total + score;   
    }, 0);
    console.log(nicTotalScore); //12120
    console.log(nicScoreList); //["12", "12"]

UPDATE: If the score field is left blank when submitted, an empty string " " instead of a score. this is registering as a 0 when the reduce method goes through the array. This doesnt affect the total, but say, for example, i wanted to then find the average score, it throws it off. any ideas there? thanks

1条回答
霸刀☆藐视天下
2楼-- · 2020-04-28 00:14

If you push() to scorelist, I'd be tempted to say it's likely an Array.

You could use reduce().

var total = scorelist.reduce(function(total, score) {
    return total + +score;
}, 0);
查看更多
登录 后发表回答