JavaScript 99Bottles - 无限循环

标签 javascript while-loop infinite-loop break decrement

(我已经知道这不是 99 瓶代码挑战的最优雅解决方案,但我真的很想知道如何在未来不重蹈覆辙。)

当它在控​​制台中运行时,它会重复 (count === 0) 条件并且只重复 "0 bottles of beer" 控制台日志,直到它崩溃.

我曾尝试在计数减至 0 后使用“break”语句,但没有取得任何成功。

let count = 99;

function bottlesOfBeer() {
    while (count >= 0) {
        if (count > 0) {
            console.log(count + " bottles of beer on the wall, " + count + " bottles of beer,");
            count--;
            console.log(" take one down, pass it around, " + count + " bottles of beer on the wall.");  
        };

        if (count === 0) {
            console.log(count + " bottles of beer on the wall, " + count + " bottles of beer. Go to the store, buy some more, 99 bottles of beer on the wall.");
        } //*this is where I tried the break statement*
    }
};

bottlesOfBeer();

最佳答案

你只在 count 大于 0 时递减它,所以它永远不会低于 0;但只要 count >= 0,循环就会继续。

关于JavaScript 99Bottles - 无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62648431/

相关文章:

javascript - 显示元素和类名

php - 从 CLI 调用时带有 PHPDocumentor 的无限循环(但通过 SSH 很好)

c - fgets 在读取/proc/PID/maps 时陷入无限循环

c - getchar() 循环不会无故结束

javascript - React Native - 在 Javascript Promise 中显示加载屏幕组件

javascript - 从 GTM 数据层中的数组中提取数据

java - 继续存储在数组中,直到有用户输入而一开始不知道元素的数量?

python - 寻求反馈,无限循环

java - 如何分解一个数字并将其数字相乘?

javascript - Azure 应用程序见解 Node js 模块无法正常工作 - Fetch API 无法加载错误