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>
以上就是js输出怎么换行的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号