【问题标题】:How can I get a line break when using the output command with javascript? [duplicate]将输出命令与 javascript 一起使用时,如何获得换行符? [复制]
【发布时间】:2021-08-26 10:21:43
【问题描述】:

我是 javascript 新手,我编写了一个非常简单的程序来测试 while 循环。 我的问题是,我不知道如何用我的代码换行。这是我的代码

<!DOCTYPE html>
<html lang="en">
<head>
<title>Phrase-o-matic</title>
</head>
<script type="text/javascript">
var scores = [60, 50, 53, 55, 61, 51, 44];
var output;
var i = 0;
while (i < scores.length) {
  output = "Bubble solution #" + i + " score: " + scores[i] ;
  document.write(output);
  i = i + 1;
}
</script>
<body>
</body>
</html>

如您所见,非常简单。但是,当我运行我的代码时,它没有换行。这是非常丑陋的。 你能给我一些修复它或更多的想法吗?非常感谢。

【问题讨论】:

  • 使用 &lt;br&gt; 元素在 HTML 中输出换行符。或者将文本放入保留空格的&lt;pre&gt; 元素中
  • document.write('&lt;br&gt;');

标签: javascript


【解决方案1】:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Phrase-o-matic</title>
</head>
<script type="text/javascript">
var scores = [60, 50, 53, 55, 61, 51, 44];
var output;
var i = 0;
while (i < scores.length) {
  output = "</br> Bubble solution #" + i + " score: " + scores[i] ;
  document.write(output);
  i = i + 1;
}
</script>
<body>
</body>
</html>

【讨论】:

    【解决方案2】:

    没有必要为输出变量赋值,因为你没有使用它。

    使用letconst 代替var 在此处阅读更多信息:https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/

    模板文字比串联更简洁,请在此处阅读更多关于它们的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

    试试这个:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>Phrase-o-matic</title>
      </head>
      <script type="text/javascript">
        const scores = [60, 50, 53, 55, 61, 51, 44];
        let i = 0;
        while (i < scores.length) {
          const output = `Bubble solution #${i} score: ${scores[i]} <br />`;
          document.write(output);
          i++;
        }
      </script>
      <body></body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2022-01-21
      • 2018-05-06
      • 2019-05-08
      • 2019-05-09
      • 1970-01-01
      相关资源
      最近更新 更多