【发布时间】:2018-07-17 16:16:23
【问题描述】:
JS新手在这里寻求一些建议。我一直在研究 Head First JavaScript Programming 这本书,它向我展示了如何将“墙上的 99 瓶啤酒”歌曲记录到控制台。这是原始代码:
var word = "bottles";
var count = 99;
while (count > 0) {
console.log(count + " " + word + " of beer on the wall");
console.log(count + " " + word + " of beer,");
console.log("Take one down, pass it around,");
count = count - 1;
if (count > 0) {
console.log(count + " " + word + " of beer on the wall.");
} else {
console.log("No more " + word + " of beer on the wall.");
}
}
没有给出答案,它暗示代码没问题但不是 100% 正确,并询问您是否可以找到缺陷并修复它。在查看控制台后,我发现 while 循环没有考虑到一旦你在歌曲中找到一瓶啤酒,“bottles”这个词就需要变为“bottle”。我在循环中添加了一些 if 语句,以便在需要时将 var 单词更改为“bottle”。该代码现在似乎可以正常工作:
var word = "bottles";
var count = 99;
while (count > 0) {
if (count == 1){
var word = "bottle"
}
console.log(count + " " + word + " of beer on the wall");
console.log(count + " " + word + " of beer,");
console.log("Take one down, pass it around,");
count = count - 1;
if (count > 0) {
if (count == 1){
var word = "bottle"
}
console.log(count + " " + word + " of beer on the wall.");
} else {
if (count < 1){
var word = "bottles"
}
console.log("No more " + word + " of beer on the wall.");
}
}
我的问题是 - 有没有比我的尝试更好或更简洁的方法来做到这一点?我觉得我的尝试有点混乱。我知道您可以为此使用 For 循环,但该示例使用了 While 循环,所以如果可能的话,我想坚持下去。
非常感谢!
【问题讨论】:
-
你可能想看看codereview.stackexchange.com。发帖前请务必通过他们的帮助中心codereview.stackexchange.com/help/on-topic
-
谢谢,Suraj - 会检查的。
标签: javascript if-statement while-loop logic conditional