我在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;
}

最佳答案

所以这是我发现的东西:


用一个分号来终止每个语句是一个好习惯,所以我说;在每个变量的末尾。
有一个函数表达式var dragonSlaying = function(){};您没有在代码末尾调用它-这就是console.log不在控制台上打印消息的原因-因此您应该添加dragonSlaying();在代码末尾。
实际上,根本不需要该函数,您可以省略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;
    }
}


其余课程祝您好运!

09-16 13:41