JavaScript添加问题

时间:2014-05-02 13:22:58

标签: javascript math

所以,我将2个角色4级加在一起(hp,攻击,力量和防御),然后比较它们。但是我遇到了问题。当数字加在一起时,它们作为一个字符串加在一起,所以输出如下。 9060951/99709940而不是246(90 + 60 + 95 + 1)/ 308(99 + 70 + 99 + 40)。这就是我在做的事情。

function calculate(player1, player2) {
    var total1 = player1.getTotal();
    var total2 = player2.getTotal();
    var differencePercentage;

    if(total1 > total2) {
        differencePercentage = total2 + "/" + total1 + " = " + (total2/total1);
    } else {
        differencePercentage = total1 + "/" + total2 + " = " + (total1/total2);
    }



    var percentage = differencePercentage;

    return percentage;
}

function Player(hp, attack, strength, defense) {
    this.hp = parseInt(hp);
    this.attack = parseInt(attack);
    this.strength = parseInt(strength);
    this.defense = parseInt(defense);

    this.getTotal = function() {
        var total = 0;
        total = hp + attack + strength + defense;
        return total;
    }
}

为什么会这样?

1 个答案:

答案 0 :(得分:5)

您正在将{I}解析为this.hp函数中的this.attackPlayer等,但不会解析为getTotal函数

试试这个

this.getTotal = function() {
    var total = 0;
    total = this.hp + this.attack + this.strength + this.defense;
    return total;
}