You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript换行失效求助:如何实现代码图形输出的换行?

Fixing Line Breaks in Your Document.Write Code

Hey there! Let's sort out why your line breaks aren't working and get that shape displaying correctly.

First, let's break down the problems with your original code:

  • You don't need to wrap document.write() in console.log() — document.write() outputs directly to the page, while console.log() sends content to the browser's developer console. This combination doesn't help with your page display.
  • The \n newline character doesn't create a line break in standard HTML. Browsers ignore these and treat them as regular spaces.

Here are two simple fixes to get your desired shape:

Option 1: Use HTML <br> Tags for Line Breaks

Replace each \n with <br> (the HTML line break tag) and remove the unnecessary console.log() calls:

document.write(' ******<br>');
document.write(' ****<br>');
document.write(' **<br>');
document.write(' ****<br>');
document.write(' ******<br>');
document.write(' ********<br>');
document.write('**********<br>');

Option 2: Use <pre> to Preserve Text Formatting

Wrap your entire text in a <pre> tag. This tag tells the browser to preserve all whitespace and line breaks exactly as you write them, so \n will work as expected:

document.write('<pre>');
document.write(' ******\n');
document.write(' ****\n');
document.write(' **\n');
document.write(' ****\n');
document.write(' ******\n');
document.write(' ********\n');
document.write('**********\n');
document.write('</pre>');

Either of these will make your shape display with proper line breaks instead of all on one line.

内容的提问来源于stack exchange,提问作者Maisha Maliha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:31:39