当我写一个while循环时,我通过将布尔变量从true更改为false来结束循环,它将“false”记录到控制台。最近我在Codecademy上遇到了这段代码:
var slaying = true;
// A bit of new math magic to calculate the odds
// of hitting the dragon. We'll cover this soon!
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 the dragon and did " + damageThisRound + " damage!");
totalDamage += damageThisRound;
if (totalDamage >= 4) {
console.log("You did it! You slew the dragon!");
slaying = false;
} else {
youHit = Math.floor(Math.random() * 2);
}
} else {
console.log("The dragon burninates you! You're toast.");
slaying = false;
}
}
该程序运行良好,但最后它记录“假”,任何人都知道发生了什么?
答案 0 :(得分:0)
我认为这是CodeAcademy的javascript引擎中的一个错误/功能,它会在结束时打印最后一个while循环的条件。
以下代码段将true
打印到控制台,即使我没有记录它。
var slaying = true;
while (slaying) {
console.log("slaying");
slaying = false;
}
while(!slaying){
console.log("not slaying..");
slaying = true;
}
所以在我看来这只是一个错误。
(我还有一个说我必须将Math.floor()
中的m大写,尽管它是。它在评论中解析单词math作为实际代码)。