【问题标题】:For loop vs. while loop in JavascriptJavascript 中的 For 循环与 while 循环
【发布时间】:2015-09-18 03:16:01
【问题描述】:

这里是初学者...

通过一个用户杀死一条龙或被吃掉的无意识概率“游戏”的在线示例。我知道游戏使用 while 循环运行,所以我尝试使用 for 循环复制它,但失败了。我很好奇为什么 for 循环不起作用,以及是否有一些明显的原因需要使用 while 循环来完成。

下面是 工作 示例,其中有一个 while 循环来提供上下文。

var slaying = true;
var youHit = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random() * 5 + 1);
var totalDamage = 0;

while (slaying) {
  if (youHit) {
    console.log("You hit the dragon and did " + damageThisRound + " damage!");
    totalDamage += damageThisRound;

    if (totalDamage >= 4) {
      console.log("You did it! You slew the dragon!");
      slaying = false;
    } else {
      youHit = Math.floor(Math.random() * 2);
    }
  } else {
    console.log("The dragon burninates you! You're toast.");
    slaying = false;
  }
}

这是 不工作 for 循环。

var youHit = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random() * 5 + 1);

for(totalDamage=0;totalDamage>3;totalDamage+=damageThisRound){
    if(youHit){
        console.log("You hit and did "+damageThisRound);
        totalDamage += damageThisRound;

        if(totalDamage>3){
            console.log("You did it! You slew the dragon!");
        } else {
            youHit = Math.floor(Math.random() * 2);
        }
    } else {
        console.log("The dragon kills you");
    }
}

谢谢

【问题讨论】:

  • 你的 for 循环永远不会开始。

标签: javascript loops for-loop while-loop


【解决方案1】:

你的循环条件是问题

var youHit, damageThisRound;
for (var totalDamage = 0; totalDamage < 4; totalDamage += damageThisRound) {
  youHit = Math.floor(Math.random() * 2);
  if (youHit) {
    //need to calculare the damage in each loop
    damageThisRound = Math.floor(Math.random() * 5 + 1);
    snippet.log("You hit and did " + damageThisRound);

  } else {
    snippet.log("The dragon kills you");
    //you need to stop the loop here
    break;
  }
}
//need this outside of the loop since the increment is in the for loop block
if (youHit) {
  snippet.log("You did it! You slew the dragon!");
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

【讨论】:

    【解决方案2】:

    for 循环中,将totalDamage 设置为0,然后调用totalDamage &gt; 3。相反,将 for 循环更改为

    for(totalDamage=0;totalDamage<3;totalDamage+=damageThisRound){
    

    换句话说,您切换了符号,因为您将变量设置为0,然后仅在变量大于大于3时继续。

    【讨论】:

    • 这修复了主要错误,是的,但似乎仍然存在一些问题。我还添加了totalDamage=4; 到最高级别的else,但脚本仍然不能完美运行。是否有可能有一个并不总是执行语句的 for 循环(在本例中为 totalDamage+=damageThisRound)?否则即使youHitfalsetotalDamage 变量也会不断增加。
    • 不,不可能在 for 循环中跳过语句的执行。也许这就是你第二个问题的答案:在这种情况下,while 循环更好,因为它使代码更清晰。对于 for 循环,我们期望在循环的每一轮中都有简单的条件和语句,非常适合浏览集合。使用 while 循环,您可以花时间提供非常清晰的代码。
    猜你喜欢
    • 2017-02-19
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 2014-03-23
    • 2020-05-15
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多