javascript - 如果 Javascript 中的变量低于零,则使用 while 循环显示消息

标签 javascript html loops

如果我是个傻子,我很抱歉。我刚刚开始学习 Javascript,正在搞循环。 我目前正在处理这段代码:

    <!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">---</button>

<p id="hpcount"></p>
<p id="demo2"></p>

<script>
var health = 30;    
document.getElementById("hpcount").innerHTML = health;

while (health < 0){
    health = 0;
    document.getElementById("demo2").innerHTML = "Game over";
    break;
}

function myFunction() {
    if (health>0){
        health -= Math.floor(Math.random() * 10)+1;
        document.getElementById("hpcount").innerHTML = health;
    }
}

</script>

</body>
</html>

这个想法是,只要生命值大于 0,按钮就会从变量“生命值”中减去一个随机整数 1-10。然后,如果它低于该值,则显示“游戏结束”消息并将生命值重置为0。 然而,虽然一旦 health>0 按钮就停止工作,但该消息就不会出现,而且无论我查看语法和结构多少次,我都无法弄清楚为什么...... 我是不是很愚蠢,错过了一些明显的东西?

最佳答案

更改此:

while (health < 0){
    health = 0;
    document.getElementById("demo2").innerHTML = "Game over";
    break;
}

function myFunction() {
    if (health>0){
        health -= Math.floor(Math.random() * 10)+1;
        document.getElementById("hpcount").innerHTML = health;
    }
}

对此:

function myFunction() {
    // if health is above 0, game is still active
    if (health>0){
        // generate a new health value
        health -= Math.floor(Math.random() * 10)+1;

        // check if the game should end
        if (health <= 0) {
            health = 0;
            document.getElementById("demo2").innerHTML = "Game over";
        } else {
            document.getElementById("hpcount").innerHTML = health;
        }
    }
}

当您学习 Javascript 时,请考虑熟悉 jQuery ,简化了 javascript 的使用并处理跨浏览器/设备兼容性问题。

关于javascript - 如果 Javascript 中的变量低于零,则使用 while 循环显示消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25594501/

相关文章:

php - 如何从html文件中的php代码打开文件

javascript - 如何直接输入按钮?

c - 如何使用平方根优化c中的循环(完美、丰富、不足)

ios - 如何检查数组中的所有字段是否包含数据

python - Python csv阅读器: loop over csv files

javascript - 在特定 FireStore 集合中执行集合组查询

javascript - 使用从 Vue 组件导入?

Javascript:如何仅对可见元素执行计数?

javascript - 无法使 Gtranslate 语言在下拉列表中工作

javascript - json 作为对象而不是字符串出现