Javascript代码以单行显示文本

时间:2017-07-18 04:14:36

标签: javascript

我正在做一个在线课程,我有一个程序要解决。我编写了代码并显示正确的输出,但我需要在一行中打印行。任何人都可以帮助我。

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

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;
}

2 个答案:

答案 0 :(得分: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);




答案 1 :(得分:1)

push()将每个字符串放入一个数组中,然后使用join()。在下面的演示中,我使用ES6 template literals作为字符串。 while()已足够,但IMO中for更好。

bottles <= 2使用.replace()输出特定字符串语法正确(即1 bottle)时添加条件。

演示

const wall = [];

for (let bottles = 99; bottles >= 1; bottles--) {
  let str = ` ${bottles} bottles of beer on the wall! ${bottles} bottles of beer! Take one down, pass it around... ${bottles - 1} bottles of beer on the wall!`;
  if (bottles <= 2) {
    str = str.replace(/1 bottles/g, `1 bottle`);
  }
  wall.push(str);
}

console.log(wall.join(''));