Looping and adding together the values generated

瘦欲@ 提交于 2020-03-06 07:31:08

问题


I have just started learning javascript, and I've hit a bit of a roadblock whilst designing the logic behind a 10 pin bowling scorecard. I would be really grateful if someone could help me figure out how, instead of my messy code below for the totalScore function, I could use a for loop that will add all of the values together. The code that I have so far is as follows. Thank you in advance!

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

回答1:


In your example above.

Replace this:

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

With this:

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



回答2:


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


来源:https://stackoverflow.com/questions/26472853/looping-and-adding-together-the-values-generated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!