gpt4 book ai didi

javascript - 让 var 根据 if 语句返回特定值

转载 作者:行者123 更新时间:2023-12-01 02:48:44 24 4
gpt4 key购买 nike

我写了一个 for 循环来唱《墙上的 99 瓶啤酒》。我正在使用 if 语句将特定值返回到 var word。当瓶子数量为 99 比 2 时,则 var word="bottles";当瓶子数量为 1 时,则 var word = "bottle"。这工作正常,但在最终迭代的最后一行,当瓶子数量为 0 并且我希望 var word 等于“bottles”时,它仍然显示为“bottle”。

var word="bottles";
for (var count = 99; count > 0; count-- ) {
document.write(count + " " + word + " of beer on the wall, <br>");
document.write(count + " " + word + " of beer.<br>" );
document.write("Take one down, pass it around,<br>");
var count2 = count - 1;
if (count2 === 1) {
word = "bottle";
}
document.write(count2 + " " + word + " of beer on the wall.<br><br>");
}

我的if语句的条件不正确吗?这就是最后三个迭代在浏览器中的样子:

墙上挂着3瓶啤酒,3瓶啤酒。拿下来一张传给大家墙上挂着两瓶啤酒。

墙上挂着两瓶啤酒,2瓶啤酒。拿下来一张传给大家墙上挂着一瓶啤酒。

墙上挂着一瓶啤酒,1瓶啤酒。拿下来一张传给大家墙上有 0 瓶啤酒。

最佳答案

您错过了重置为瓶子else部分,请尝试使用此脚本

var word="bottles";
for (var count = 99; count > 0; count-- ) {
document.write(count + " " + word + " of beer on the wall, <br>");
document.write(count + " " + word + " of beer.<br>" );
document.write("Take one down, pass it around,<br>");
var count2 = count - 1;
if (count2 === 1) {
word = "bottle";
} else
{ word = "bottles";
}
document.write(count2 + " " + word + " of beer on the wall.<br><br>");
}

关于javascript - 让 var 根据 if 语句返回特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47108947/

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