javascript - Codecademy JavaScript 错误

标签 javascript

我正在 Codecademy 上学习 javascript。然后突然我遇到了错误“哎呀,再试一次。请确保在控制台上打印一条消息!”

 var slaying = true
 var youHit = Math.floor(Math.random()* 2)
 var damageThisRound = Math.floor(Math.random()*5 + 1)
 var totalDamage = 0
 var dragonSlaying = function() {
     while(slaying){   
         if(youHit){   
             console.log("You hit that bastard");
             totalDamage += damageThisRound;
             if(totalDamage >= 4){
                 console.log("The dragon has been slain");
                 slaying = false;
             } else {
                 youHit = Math.floor(Math.random() * 2);
             }
         } else {
             console.log("You have been defeated; you missed the slimy thing! Maybe next time.");   
             slaying = false;
         }
    }       
    slaying = false;
}

最佳答案

这就是我的发现:

  1. 用分号结束每个语句是一个好习惯,所以我把 ;在每个变量的末尾。
  2. 有一个函数表达式 var DragonSlaying = function() {};您没有在代码末尾调用它 - 这就是 console.log 没有在控制台上打印消息的原因 - 所以您应该添加 DragonSlaying();在代码末尾。
  3. 实际上,根本不需要这个函数,你可以省略 var DragonSlaying = function() {};并且代码将完美运行。

这是更正后的代码:

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 that bastard");
        totalDamage += damageThisRound;
            if(totalDamage >= 4){
                console.log("The dragon has been slain");
                slaying = false;
            } else {
            youHit = Math.floor(Math.random() * 2);
            }
    } else {
        console.log("You have been defeated; you missed the slimy thing! Maybe next time.");   
        slaying = false;
    }
}       

祝余下的类(class)顺利!

关于javascript - Codecademy JavaScript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35375025/

相关文章:

javascript - 通过 CRUD API 分页

javascript - 如何在 Angular 过滤器中包含 "string includes"函数

java - deployjava.getJREs 不适用于 Windows 7 64 位 jre

javascript - 如何创建一个左、中、右各有图标的列表项?

javascript - 使用 Google Maps Api 和外部 Json 文件

javascript - 读取 CSV 后数组的最大长度(JavaScript)

javascript - 如何隐藏使用 Electron 构建的 nodeJS 解决方案的源代码(asar 文件)?

javascript - 无法从api获取数据

javascript - ASP.net MVC session 超时持续时间

javascript - 无法在 Chrome 存储中存储和检索