如何优化99 Bottles of Beer的JavaScript代码使其更专业?
优化《99 Bottles of Beer》JavaScript实现的几个方向
你的代码已经实现了核心功能,但可以从可读性、可维护性、代码规范这几个维度优化,下面是具体的优化方案和分析:
原代码存在的核心问题
- 用
var重复声明变量,因变量提升容易导致意外的bug - 循环体内手动执行
numberOfBottles--,和循环条件的自减逻辑冲突,会跳过部分数值 - 字符串拼接重复冗余,相同的短语多次构造
- 边界场景(1瓶、0瓶、无剩余的情况)处理逻辑分散,可读性差
优化后的代码
// 提取复用函数:根据瓶子数量生成对应的短语 function getBottlePhrase(count) { if (count === 0) return "No more bottles"; if (count === 1) return "1 bottle"; return `${count} bottles`; } // 循环生成每一段歌词 for (let count = 99; count >= 1; count--) { const currentPhrase = getBottlePhrase(count); const nextPhrase = getBottlePhrase(count - 1); console.log(`${currentPhrase} of beer on the wall, ${currentPhrase} of beer.`); console.log(`Take one down and pass it around, ${nextPhrase} 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.");
关键优化点解析
- 使用
let替代var:let有块级作用域,避免变量提升带来的意外覆盖,代码更安全 - 提取复用函数
getBottlePhrase:把瓶子数量转对应短语的逻辑抽离,避免重复判断,后续修改规则(比如调整语法)只需要改这一个函数 - 简化循环逻辑:循环从99到1,每次循环直接用
count-1作为下一个数量,不再手动修改循环变量,逻辑更清晰 - 模板字符串拼接:用
`${}`替代传统的+拼接,字符串结构更直观,减少语法错误 - 边界场景集中处理:把0瓶、1瓶的判断统一放在函数里,代码逻辑更紧凑,可读性更强
- 拆分最后两段歌词:原代码循环里的边界处理容易混乱,单独提取最后两段,逻辑更清晰
内容的提问来源于stack exchange,提问作者Fatima BT
相关产品推荐
相关产品推荐

