如何修改JavaScript代码添加《99瓶啤酒》歌词的最后段落
修改JavaScript代码实现完整《99瓶啤酒》歌词
当前你的代码生成的最后一段歌词是:
1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around,
no more bottle of beer on the wall.
你需要添加以下首字母大写N开头的收尾段落:
No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
修改后的代码
var beer = 99; // 生成99到1瓶的歌词段落 while (beer > 0) { var currentBottleWord = beer === 1 ? "bottle" : "bottles"; // 输出当前行歌词 console.log(`${beer} ${currentBottleWord} of beer on the wall, ${beer} ${currentBottleWord} of beer.`); console.log("Take one down and pass it around,"); beer--; var nextBottleWord = beer === 1 ? "bottle" : "bottles"; var nextBeerCount = beer === 0 ? "no more" : beer; // 输出下一行歌词 console.log(`${nextBeerCount} ${nextBottleWord} of beer on the wall.\n`); } // 追加收尾的歌词段落 console.log("No more bottles of beer on the wall, no more bottles of beer."); console.log("Go to the store and buy some more, 99 bottles of beer on the wall.");
关键修改说明
- 调整循环范围:把原循环的
beer >= 0改成beer > 0,让循环只处理99到1瓶的内容,留出发起收尾段落的空间。 - 修复单复数错误:原代码中"no more"后面误用了单数"bottle",现在统一改成正确的复数"bottles"。
- 拆分输出格式:把原代码中一行挤在一起的歌词拆分成单独行输出,和标准歌词格式一致。
- 新增收尾逻辑:循环结束后单独输出你需要的首字母大写的收尾段落,确保内容完全符合要求。
内容的提问来源于stack exchange,提问作者Satin Wichapha
相关产品推荐
相关产品推荐

