循环完成后循环打印时的javascript

时间:2016-12-14 13:40:55

标签: javascript loops object while-loop

所以这就是我想要做的事情:

两个对象有hp和power变量。我想在他们之间做一场战斗。逻辑是做一个这样的循环:object1HP-object2Power,Object2HP - Object2Power。当其中一个对象的HP为0或更低时 - 打印谁赢了。

这是我到目前为止所做的:



 this.battle = function(other) {
    	do {
           this.hp - other.power;
           other.hp - this.power;
        }
    	while (this.hp <=0 || other.hp <=0);
        
        if(this.hp <=0) {
            console.log(this.name + " won!");
        } else {
            console.log(other.name + " won!");
        }
   }
&#13;
&#13;
&#13;

我知道这可能是一团糟。谢谢!

2 个答案:

答案 0 :(得分:0)

我不确定你的问题是什么。代码段是否有效? 我眼中浮现的一个微小细节就是你可能想写的

this.hp -= other.power;
other.hp -= this.power;

你错过了&#34; =&#34;,你得到一个无限循环,因为变量保持不变。

答案 1 :(得分:0)

这应该是正常工作的代码段:

&#13;
&#13;
this.battle = function(other) {
    	do {
           this.hp = this.hp - other.power; //Need to set this.hp equal to it, or nothing is changing
           other.hp = other.hp - this.power;
        }
    	while (this.hp >=0 && other.hp >=0); //You want to keep running the loop while BOTH players have HP above 0
        
        if(this.hp <=0) { //If this has less than zero HP, then the other person won, so you need to inverse it
            console.log(other.name + " won!");
        } else {
            console.log(this.name + " won!");
        }
   }
&#13;
&#13;
&#13;

您遇到的第一个问题是您在更改变量后没有设置变量。只让this.hp - other.power不将值保存到任何变量中。因此this.hp在每个循环后保持不变。要解决此问题,只需通过说出this.hp

将新值设置为this.hp = this.hp - other.power

第二个问题是你的while循环条件不正确。说this.hp <= 0 || other.hp <= 0说&#34;如果其中一个玩家的hp小于零,那就继续跑步&#34;你正在寻找的是&#34;如果两个玩家的hp都大于零,那么继续跑步&#34;

最后,您在最终if声明中的逻辑是错误的。我在代码片段中添加了一些注释,引导您完成更改。 如果出现问题,请告诉我,希望这会有所帮助。