How do I create a new line in Javascript?

2019-01-05 00:05发布

var i;
for(i=10; i>=0; i= i-1){
   var s;
   for(s=0; s<i; s = s+1){
    document.write("*");
   }
   //i want this to print a new line
   /document.write(?);

}

I am printing a pyramid of stars, I can't get the new line to print.

15条回答
祖国的老花朵
2楼-- · 2019-01-05 00:55

Use the \n for a newline character.

document.write("\n");

You can also have more than one:

document.write("\n\n\n"); // 3 new lines!  My oh my!

However, if this is rendering to HTML, you will want to use the HTML tag for a newline:

document.write("<br>");

The string Hello\n\nTest in your source will look like this:

Hello!

Test

The string Hello<br><br>Test will look like this in HTML source:

Hello<br><br>Test

The HTML one will render as line breaks for the person viewing the page, the \n just drops the text to the next line in the source (if it's on an HTML page).

查看更多
Animai°情兽
3楼-- · 2019-01-05 00:58

For a string I just write "\n" to give me a new line. For example, typing console.log("First Name: Rex" + "\n" + "Last Name: Blythe"); Will type:

First Name: Rex

Last Name: Blythe

查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-05 01:04

Use a <br> tag to create a line break in the document

document.write("<br>");

Here's a sample fiddle

查看更多
SAY GOODBYE
5楼-- · 2019-01-05 01:04

\n dosen't work. Use html tags

document.write("<br>");
document.write("?");
查看更多
forever°为你锁心
6楼-- · 2019-01-05 01:04

If you are using a JavaScript file (.js) then use document.write("\n");. If you are in a html file (.html or . htm) then use document.write("<br/>");.

查看更多
可以哭但决不认输i
7楼-- · 2019-01-05 01:05

Alternatively, write to an element with the CSS white-space: pre and use \n for newline character.

查看更多
登录 后发表回答