javascript - Javascript 中的 For 循环与 while 循环

标签 javascript loops for-loop while-loop

完全是新手...

研究一个用户杀死龙或被吃掉的盲目概率“游戏”的在线示例。我知道游戏使用 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");
    }
}

谢谢

最佳答案

你的循环条件是问题所在

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>

关于javascript - Javascript 中的 For 循环与 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31153285/

相关文章:

python - For 循环在另一个数据框中查找行

javascript - for-in-Loop 之后执行代码的问题

javascript - 从具有相同键的对象创建一个新数组

javascript - 两个下拉列表,第二个下拉列表填充数据库中的值

Javascript 输出导致意外标记 <

javascript - 递归 JQuery 以在文本中格式化 HTML 节点值

python - Pandas:迭代并插入具有组内条件的列复杂问题

javascript - 从url中获取id值并解析为def

python - 如何在循环期间更新 Django 查询集中的数据?

javascript - 循环遍历数组并过滤电子邮件