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()inconsole.log()—document.write()outputs directly to the page, whileconsole.log()sends content to the browser's developer console. This combination doesn't help with your page display. - The
\nnewline 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
相关产品推荐
相关产品推荐

