JavaScript 99Bottles - 无限循环

JavaScript 99Bottles - Infinite Loop

(我已经知道这不是 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.

循环就会继续

while (count >= 0) 变成 while (count > 0) 就可以了!

问题是,当它达到零时,您只是记录消息而不再减少它,因此它保持为零并且 (count >= 0) 始终为真。

这是更正后的代码:

function bottlesOfBeer() {
  var count = 99;
  while (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.");  
  }
  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.");
};

bottlesOfBeer();

请阅读并理解 - 如果您有任何问题,请提出。
在代码中,count 被设置为 99。
while 循环在 count 变为零时停止。
当循环存在时,count 为零,并记录歌曲的相应行。
我删除了空行...
除此之外 - 你的代码非常整洁:没有奇怪的缩进(你不会相信我所看到的 - 并不是说​​它会影响执行,只是更容易阅读)。