Javascript for循环不起作用(总计添加数字)

时间:2014-10-21 08:38:10

标签: javascript for-loop

我正在使用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.scorecard [0] .rollOne + this.scorecard [0] .rollTwo,但for循环(即使它看起来正确)似乎不起作用。任何帮助将不胜感激:)

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

你必须在你的游戏中添加框架

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。

答案 2 :(得分:0)

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

  game.Add(frame1);
   game.Add(frame2);
相关问题