我刚开始学习javascript,在设计10针保龄球记分卡背后的逻辑时,我遇到了一些障碍。如果有人可以帮我弄清楚如何使用forScore循环将所有值加在一起,而不是下面的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)
};
答案 0 :(得分:0)
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;
};
答案 1 :(得分:0)
在上面的示例中。
替换它:
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)+
};
&#13;
有了这个:
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;
};
&#13;