javascript:程序卡住了

时间:2013-10-06 13:58:34

标签: javascript web

我在 codecademy 上学习javascript。我提交时,以下程序卡住了。我是新手,所以我找不到这个bug。我下载了 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.")
    }
}

5 个答案:

答案 0 :(得分:2)

根据我的理解。您需要在else部分设置slaying = false,否则程序将被抛入无限循环。

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

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

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

答案 1 :(得分:0)

是肯定的。如果你使用Chrome,你可以使用内置的Dev Tools或(如果使用Firefox)你可以使用FireBug扩展

答案 2 :(得分: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.")
    }
}

答案 3 :(得分: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;
    }
}

你错过了在别人案件中杀人的错误。所以,如果你不这样做,那就是无限循环。

答案 4 :(得分:0)

在else语句后添加false(包含龙击败了你)。喜欢这个

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

否则,它是一个无限循环,导致一个人的浏览器崩溃。如果它是JAVA或类似的东西,游戏不会停止,但它是JS - 你不能没有结束循环。