You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:54:04