0

我正在codecademy上学习 javascript 。以下程序在我提交时卡住了。我是新手,所以我找不到错误。我下载了Aptana Studio,但我不知道如何调试:(。有什么方法可以跟踪代码吗?提前谢谢。

var slaying = true;
var youHit = Math.random() > 0.5;
var damageThisRound = Math.floor(5 * Math.random());
var totalDamage = 0;

while (slaying) {
    if (youHit) {
        console.log("You hit the dragon.");
        totalDamage += damageThisRound;
        if (totalDamage >= 4) {
            console.log("You've stew the dragon!");
            slaying = false;
        } else {
            youHit = Math.random() > 0.5;
        }
    } else {
        console.log("The dragon defeated you.")
    }
}
4

5 回答 5

2

据我了解。需要slaying = false在else部分进行设置,否则程序会陷入循环。

} else {
    slaying = false; //Added here - Breaks the while() condition
    console.log("The dragon defeated you.")
}

很简单,当The dragon defeated you.杀戮停止时。(双关语)

对于调试使用 Chrome 的内置Developer toolsFirebugFirefox。两者都用于F12在您选择的浏览器中访问。

于 2013-10-06T14:00:57.410 回答
0

是的。如果你使用 Chrome,你可以使用内置的开发工具,或者(如果使用 Firefox)你可以使用 FireBug 扩展

于 2013-10-06T14:01:13.253 回答
0
var slaying = true;
var youHit = Math.random() > 0.5;
var damageThisRound = Math.floor(5 * Math.random());
var totalDamage = 0;

while (slaying) {
    if (youHit) {
        console.log("You hit the dragon.");
        totalDamage += damageThisRound;
        if (totalDamage >= 4) {
        console.log("You've stew the dragon!");
            slaying = false;
        } else {
        youHit = Math.random() > 0.5;
        }
    } else {
        //add this line
        slaying = false;    
        console.log("The dragon defeated you.")
    }
}
于 2013-10-06T14:02:53.587 回答
0
var slaying = true;
var youHit = Math.random() > 0.5;
var damageThisRound = Math.floor(5 * Math.random());
var totalDamage = 0;

while (slaying) {
    if (youHit) {
        console.log("You hit the dragon.");
        totalDamage += damageThisRound;
        if (totalDamage >= 4) {
        console.log("You've stew the dragon!");
            slaying = false;
        } else {
        youHit = Math.random() > 0.5;
        }
    } else {
        console.log("The dragon defeated you.");
        slaying=false;
    }
}

在其他情况下,您错过了杀死假。所以如果你不这样做,它会处于无限循环中。

于 2013-10-06T14:09:41.180 回答
0

在 else 语句后添加 false(包含龙打败了你)。像这样

} else {
    console.log("The dragon defeated you.");
    slaying=false;
}

否则就是死循环,导致浏览器崩溃。如果是 JAVA 或类似的东西,游戏不仅会停止,而且是 JS——你不可能有一个没有结束的循环。

于 2013-10-06T15:28:34.137 回答