Codecademy Javascript Error

Codecademy Javascript Error

本文关键字:Error Javascript Codecademy      更新时间:2023-09-26

我在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 dragonSkilling = function() {}; 你没有在代码末尾调用它 - 这就是控制台.log没有在控制台上打印消息的原因 - 所以你应该在代码末尾添加dragonSlaying();
  3. 实际上,根本不需要这个函数,你可以省略var dragonSlay=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;
    }
}       

祝课程其余部分好运!

你必须意识到,Codecademy希望你以特定的方式做事,尽管方向有时可能很模糊。

因此,工作代码有时甚至无法进入下一课。确保完全遵循他们的指示,并确保注意最后一步,有时包括调用函数。

代码末尾的 PS 分号,可以将其视为语句或命令的结尾。 如果你不以分号结尾,代码就会运行到下一行,然后它就不再起作用了。