使用对象中的数组计算总和

时间:2020-02-22 21:16:10

标签: arrays object for-loop

我是js的新手,我想计算数组中的总和。问题是我的数组位于对象-游戏中。这是我的代码:

var game = {
    fullName: 'Mark Visp', 
    score: [110, 320, 50, 80],
    sumScore: function () {
        this.total = [];
        var total = 0;

        for (i = 0; i < this.score.length; i++) {
            total = total + this.score[i]; 
            } 
        return total
    }  
}  
game.sumScore();
console.log(game); 

我缺少什么?

先谢谢了。

1 个答案:

答案 0 :(得分:0)

请替换为以下代码

var game = {
    fullName: 'Mark Visp', 
    score: [110, 320, 50, 80],
    total: 0,
    sumScore: function () {
        var _total = 0;

        for (i = 0; i < this.score.length; i++) {
            _total = _total + this.score[i]; 
            } 
        this.total = _total;
    }  
}  
game.sumScore();
console.log(game);