【问题标题】:javascript while loop print after loop done循环完成后的javascript while循环打印
【发布时间】:2017-04-29 20:54:27
【问题描述】:

这就是我想要做的:

两个对象有 hp 和 power 变量。我想在他们之间进行一场战斗。逻辑是做一个这样的循环:object1HP-object2Power,Object2HP-Object2Power。当其中一个物体的生命值为 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!");
        }
   }

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

【问题讨论】:

  • 您需要将循环更改为 and (&&) and > 0,这样它就会一直持续到一个小于或等于零为止

标签: javascript loops object while-loop


【解决方案1】:

我不确定你的问题是什么。代码 sn-p 有效吗? 一个让我眼前一亮的小细节是,你可能想写

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

你错过了“=”,你会得到一个无限循环,因为变量保持不变。

【讨论】:

    【解决方案2】:

    这应该是工作代码 sn-p:

    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!");
            }
       }

    您遇到的第一个问题是您在更改变量后没有设置变量。仅仅拥有this.hp - other.power 不会将值保存到任何变量中。所以this.hp 在每次循环后保持不变。为了解决这个问题,只需通过说this.hp = this.hp - other.power 将新值设置为this.hp

    第二个问题是您的 while 循环条件不正确。说this.hp &lt;= 0 || other.hp &lt;= 0 是在说“如果任一玩家的 hp 小于零,请继续奔跑”,而您正在寻找的是“如果两个玩家的 hp 都大于零,请继续奔跑”

    最后,你在最后的if 语句中的逻辑是错误的。我在代码 sn-p 上添加了一些 cmets 来引导您完成更改。 如果还有问题,请告诉我,希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 2021-08-30
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      • 2022-10-12
      • 1970-01-01
      相关资源
      最近更新 更多