简体   繁体   中英

Codecademy Javascript Error

I was learning javascript on Codecademy. Then all of a sudden I encountered the error "Oops, try again. Make sure you print a message onto the console!"

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

So here's what I found:

  1. It's a good habit to terminate each statement with a semicolon, so I put ; at the end of each variable.
  2. There is a function expression var dragonSlaying = function() {}; which you didn't call at the end of your code - this is the reason why console.log didn't print a message onto the console - so you should add dragonSlaying(); at the end of your code.
  3. Actually, there is no need for the function at all, you could just omit var dragonSlaying = function() {}; and the code will work perfectly.

Here's the corrected code:

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

Good luck with the rest of the course!

You will have to realize that Codecademy wants you to do things in a specific manner, although the directions can be vague at times.

A working code, sometimes doesnt even go through to the next lesson because of this. Make sure to follow their directions completely and also be sure to watch out for the last step which sometimes includes calling the function.

ps semicolons at the end of code, think of it as concluding a statement or command. if you dont conclude with semicolons the code just runs on to the next lines and then it just doesnt work anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM