我正在教科书中做练习,但没有提供作业的答案或示例。这是古老的 99 Bottles of Beer on the wall javascript 程序。在网上搜索后,我只找到了一些示例,这些示例的编码方式与本书迄今为止教我的方式非常不同。我的问题是,当我到达底部(1 瓶)时,第一行总是显示“1 瓶”,即使其余的调整为“1 瓶”。我不知道我做错了什么,但我渴望学习!感谢大家!我已经包含了一个 jsfiddle。
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.");
if (count === 1)
word = "bottle";
} else {
console.log("No more bottles of beer on the wall.");
}
}
最佳答案
您的代码记录“墙上有 1 瓶啤酒”的原因。是因为您在记录该表达式之后更改了 word
的值。要在对代码进行最少更改的同时解决此问题,您只需颠倒 word
和 console.log
的条件赋值的顺序即可:
if (count > 0) {
if (count === 1) {
word = "bottle";
}
// Note that the log will occur after the word = "bottle" assigment.
console.log(count + " " + word + " of beer on the wall.");
} else {
console.log("No more bottles of beer on the wall.");
}
此外,我想指出,我在 word = "bottle";
block 周围添加了大括号。这些不是必需的,但我认为,它们可以使代码更具可读性。乍一看,您的 else
block 看起来对应于 if (count === 1)
,但它实际上对应于 if (count > 0)
.
关于Javascript 在实现时似乎跳过了一行(如果 count === 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37091825/