循环并将生成的值相加

Looping and adding together the values generated

本文关键字:循环      更新时间:2023-09-26

我刚开始学习javascript,在设计10杆保龄球记分卡背后的逻辑时遇到了一些障碍。如果有人能帮我弄清楚如何使用for循环将所有值相加,而不是下面针对totalScore函数的混乱代码,我将不胜感激。到目前为止,我拥有的代码如下。提前谢谢!

function Game() {
    this.scorecard = []
};

Game.prototype.add = function(frame) {
    this.scorecard.push(frame)
};
Game.prototype.totalScore = function() {
(this.scorecard[0].rollOne + this.scorecard[0].rollTwo)+
(this.scorecard[1].rollOne + this.scorecard[0].rollTwo)+
(this.scorecard[2].rollOne + this.scorecard[0].rollTwo)+
(this.scorecard[3].rollOne + this.scorecard[0].rollTwo)+
(this.scorecard[4].rollOne + this.scorecard[0].rollTwo)+
(this.scorecard[5].rollOne + this.scorecard[0].rollTwo)+
};

function Frame() {};
Frame.prototype.score = function(first_roll, second_roll) {
this.rollOne = first_roll;
this.rollTwo = second_roll;
return this
};
Frame.prototype.isStrike = function() {
return (this.rollOne === 10);
};
Frame.prototype.isSpare = function() {
return (this.rollOne + this.rollTwo === 10) && (this.rollOne !== 10)
};

在上面的例子中。

替换此:

Game.prototype.totalScore = function() {
(this.scorecard[0].rollOne + this.scorecard[0].rollTwo)+
(this.scorecard[1].rollOne + this.scorecard[0].rollTwo)+
(this.scorecard[2].rollOne + this.scorecard[0].rollTwo)+
(this.scorecard[3].rollOne + this.scorecard[0].rollTwo)+
(this.scorecard[4].rollOne + this.scorecard[0].rollTwo)+
(this.scorecard[5].rollOne + this.scorecard[0].rollTwo)+
};

有了这个:

Game.prototype.totalScore = function() {
  var result = 0;
  for (var i = 0; i<6; i++) {
    result += this.scorecard[i].rollOne + this.scorecard[0].rollTwo;
  }
  return result;
};

  Game.prototype.totalScore = function() {
    total = 0;
    for(i = 0; i < this.scorecard.length; i++)
    {
       total +=this.scorecard[i].rollOne + this.scorecard[0].rollTwo;
    }
    return total;
};