循环的Javascript;不起作用(把数字加到总数上)

Javascript for loop doesn't work (adding numbers to a total)

本文关键字:数字 Javascript 不起作用 循环      更新时间:2023-09-26

我正在使用Jasmine进行JS测试,不幸的是,我无法通过以下测试。

it('should know the total game score', function() {
    frame1 = new Frame;
    frame2 = new Frame;
    game = new Game;
    frame1.score(3, 4);
    frame2.score(5, 5);
    expect(game.totalScore()).toEqual(17)
});

我得到的错误消息如下:错误:应为0,等于17。

代码如下:

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

Game.prototype.add = function(frame) {
    this.scorecard.push(frame)
};
// Why is this not working!!???
Game.prototype.totalScore = function() {
    total = 0;
    for(i = 0; i < this.scorecard.length; i++)
    {
       total +=this.scorecard[i].rollOne + this.scorecard[i].rollTwo;
    }
    return total;
}; 
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)
};

手动将数字相加似乎有效,例如total=game.scoreca[0].rollOne+this.scoreca[0].rollTwo,但for循环(即使看起来正确)似乎不起作用。如有任何帮助,我们将不胜感激:)

我不太确定,但您似乎没有调用"Add"方法,因此没有数据添加到记分卡中。

我猜你必须将帧添加到你的游戏中

it('should know the total game score', function () {
    frame1 = new Frame;
    frame2 = new Frame;
    game = new Game;
    // those lines are missing
    game.add(frame1);
    game.add(frame2);
    frame1.score(3, 4);
    frame2.score(5, 5);
    expect(17).toEqual(game.totalScore())
});

否则,记分卡数组为空,因此总分等于0。

丢失(因此没有数据添加到记分卡中。)

  game.Add(frame1);
   game.Add(frame2);