(我已经知道这不是 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
,循环就会继续。
这是更正后的代码:
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
为零,并且记录歌曲的相应行。将
while (count >= 0)
变成 while (count > 0)
就可以开始了!
问题是,当它达到零时,您只需记录消息而不再减少它,因此它保持为零并且
(count >= 0)
始终为真。
*let x = 99
let y = x - 1
function beer() {
while (x > 1) {
x--
y--
console.log(x + " bottles of bear on the wall, " + x + " bottles of bear. Take one down and pass it around, " + y + " bottles of bear on the wall.")
}
}*