gpt4 book ai didi

javascript - 我的 JS 代码适合 '99 Bottles of Beer on the Wall' 歌曲吗?

转载 作者:行者123 更新时间:2023-12-03 02:32:50 27 4
gpt4 key购买 nike

JS新手在这里寻求一些建议。我一直在阅读《Head First JavaScript 编程》一书,它向我展示了如何将“99 Bottles of Beer on the Wall”歌曲记录到控制台。原始代码如下:

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 循环,因此如果可能的话,我想坚持使用该循环。

非常感谢!

最佳答案

您可以通过用简洁的三元表达式替换那些庞大的 if else 语句来稍微整理一下逻辑:

while (count > 0) {
var bottle = count == 1 ? "bottle" : "bottles";
console.log(count + " " + word + " of beer on the wall");
console.log(count + " " + word + " of beer,");
console.log("Take one down, pass it around,");
--count;
var bottle = count == 1 ? "bottle" : "bottles";
console.log(count + " " + word + " of beer on the wall.");
}

这从语法上假设短语0 Bottles of beer on the wall是正确的,并且是我们想要使用的。这对我来说听起来不错,但我想从技术上讲 0 或 1 瓶都应该是单数。

关于javascript - 我的 JS 代码适合 '99 Bottles of Beer on the Wall' 歌曲吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48662701/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com