javascript 中换行的方法
在 JavaScript 中,有几种方法可以在输出中换行:
1. 使用 "\n" 转义字符
最简单的方法是在字符串中使用 "\n" 转义字符,它代表换行符。例如:
<code class="javascript">console.log("行 1\n行 2\n行 3");</code>输出:
<code>行 1 行 2 行 3</code>
2. 使用多行字符串
JavaScript 支持多行字符串,可以用反引号 (`) 编写。换行符将自动添加到行末:
<code class="javascript">console.log(`行 1 行 2 行 3`);</code>
输出:
<code>行 1 行 2 行 3</code>
3. 使用 CSS 的 "white-space" 属性
如果输出是 DOM 元素的内容,可以使用 CSS 的 "white-space" 属性来控制换行。例如:
<code class="html"><div id="output" style="white-space: pre-line"> 行 1 行 2 行 3 </div></code>
<code class="javascript">document.getElementById("output").innerHTML = "行 1\n行 2\n行 3";</code>输出:
<code>行 1 行 2 行 3</code>
4. 使用 Template Literals
ES6 中引入了 Template Literals,可以使用 \n 换行符:
<code class="javascript">console.log(`行 1 行 2 行 3`);</code>
输出:
<code>行 1 行 2 行 3</code>










