JavaScript使用while循环实现99瓶啤酒歌词输出异常如何解决?
99瓶啤酒JS代码问题排查与修复方案
代码存在的核心问题
- 循环体范围错误:
count--递减语句和console.log(output)打印语句都写在了while的大括号外部,导致循环内部永远不会修改count的值,代码会直接陷入死循环,永远不会执行到打印逻辑。 - 未适配边界文本:当瓶数为1时,单位应该是单数
bottle而非复数bottles;当瓶数为0时,首句文本需要改为No more bottles,且最后一段的收尾逻辑需要调整,不能继续执行“拿一瓶”的动作,需要替换为购买新啤酒的描述。 - 计数终止逻辑不合理:原逻辑中计数到0之后还要减1得到-1,不符合歌词的最终收尾规则。
修正后的可运行代码
function beer() { let count = 99; // 处理瓶数单复数、0值的文本适配工具 const getBottleText = (num) => { if (num === 0) return 'No more bottles'; if (num === 1) return '1 bottle'; return `${num} bottles`; }; while (count >= 0) { const currentBottle = getBottleText(count); let nextBottle, actionText; if (count === 0) { actionText = 'Go to the store and buy some more'; nextBottle = getBottleText(99); } else { actionText = 'Take one down and pass it around'; nextBottle = getBottleText(count - 1); } // 输出当前段歌词 console.log(`${currentBottle} of beer on the wall, ${currentBottle.toLowerCase()} of beer. ${actionText}, ${nextBottle.toLowerCase()} of beer on the wall.`); // 每轮循环结束递减计数 count--; } } beer();
关键调整说明
- 将计数递减、打印逻辑都移到了
while循环内部,避免死循环,确保每轮循环输出一段歌词 - 新增单复数和0值的文本适配,完全匹配标准歌词的文本规则
- 补充了count为0时的特殊收尾逻辑,符合歌词的完整闭环要求
内容的提问来源于stack exchange,提问作者Samar
相关产品推荐
相关产品推荐

