gpt4 book ai didi

用于在单行中显示文本的 Javascript 代码

转载 作者:行者123 更新时间:2023-11-30 15:10:38 26 4
gpt4 key购买 nike

我正在上在线类(class),我有一个程序要解决。我已经编写了代码并且它显示了正确的输出,但我需要在一行中打印这些行。任何人都可以帮助我。

如何在一行中显示多行文本。我写的代码如下:

var num = 99;

while (num >= 1) {
if (num > 2) {
console.log("" + num + " bottles of juice on the wall! " + num + " bottles of juice! Take one down, pass it around... " + (num - 1) + " bottles of juice on the wall!");
} else if (num === 2) {
console.log("" + num + " bottles of juice on the wall! " + num + " bottles of juice! Take one down, pass it around... " + (num - 1) + " bottle of juice on the wall!");
} else {
console.log("" + num + " bottle of juice on the wall! " + num + " bottle of juice! Take one down, pass it around... " + (num - 1) + " bottle of juice on the wall!");
}

num = num - 1;
}

最佳答案

作为@Nisarg Shah在评论中提到,您可以在循环外声明一个全局变量,循环内的代码不断添加。

一旦循环结束,代码可以使用 console.log 将存储在变量中的字符串输出为一行。

var output = "";

var num = 99;

while (num >= 1) {
var pluralSuffix = num != 1 ? "s" : "";
var nextNum = num - 1;
var nextPluralSuffix = nextNum != 1 ? "s" : "";

output += num + " bottle" + pluralSuffix + " of juice on the wall! " + num + " bottle" + pluralSuffix + " of juice! Take one down, pass it around... " + nextNum + " bottle" + nextPluralSuffix + " of juice on the wall! ";

num = nextNum;
}

console.log(output);

关于用于在单行中显示文本的 Javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45157394/

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