所以,我将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;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
您解析成整数的this.hp,this.attack等你的Player功能,但不进getTotal功能
试试这个
this.getTotal = function() {
var total = 0;
total = this.hp + this.attack + this.strength + this.defense;
return total;
}
Run Code Online (Sandbox Code Playgroud)