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条回答
ゆ 、 Hurt°
2楼-- · 2019-01-05 00:44

For adding a new line use

document.write("<br>")

For adding space use

document.write("&nbsp;")

or

document.write("\n")
查看更多
甜甜的少女心
3楼-- · 2019-01-05 00:45

how about:

document.write ("<br>");

(assuming you are in an html page, since a line feed alone will only show as a space)

查看更多
小情绪 Triste *
4楼-- · 2019-01-05 00:46

In html page:

document.write("<br>"); 

but if you are in JavaScript file, then this will work as new line:

document.write("\n");
查看更多
可以哭但决不认输i
5楼-- · 2019-01-05 00:46

To create a new line, symbol is '\n'

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('\n');

}

If you are outputting to the page, you'll want to use "<br/>" instead of '/n';

Escape characters in JavaScript

查看更多
孤傲高冷的网名
6楼-- · 2019-01-05 00:48

document.writeln() is what you are looking for or document.write('\n' + 'words') if you are looking for more granularity in when the new line is used

查看更多
神经病院院长
7楼-- · 2019-01-05 00:51

\n --> newline character is not working for inserting a new line.

    str="Hello!!";
    document.write(str);
    document.write("\n");
    document.write(str);

But if we use below code then it works fine and it gives new line.

    document.write(str);
    document.write("<br>");
    document.write(str);

Note:: I tried in Visual Studio Code.

查看更多
登录 后发表回答