我正在 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;
}
}
祝余下的类(class)顺利!
关于javascript - Codecademy JavaScript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35375025/