[英]How to print a half pyramid in javascript
The code works but I don't want the inner for loop to take me to the new line. 该代码有效,但是我不希望内部的for循环将我带到新行。
for (i = 0; i < 5; i++) { for (j = 1; j <= i; j++) { console.log('*'); } console.log(); } console.log('-----------------');
console.log
will automatically break the line. console.log
将自动中断。 Concatenate to a string instead of a log. 连接到字符串而不是日志。 Log at the end.
登录到最后。
let str = ''; for(i = 0; i <= 5 ; i++) { for(j = 1; j <= i; j++) { str += '*'; } str += '\\n'; } console.log(str);
You can do this way, with the help of a string variable: 您可以在字符串变量的帮助下进行以下操作:
for (i = 0; i < 5; i++) { var str = ''; for (j = 1; j <= i; j++) { str+='*'; } console.log(str); } console.log('-----------------');
You need to break the line with the console.log
you can also controle the space between * with output+='*' + " ";
您需要使用
console.log
来换行,也可以使用output+='*' + " ";
来控制*之间的空格output+='*' + " ";
function pyramid() { var total = 5; var output=""; for (var i = 1; i <= total; i++) { for (var j = 1; j <= i; j++) { output+='*' + " "; } console.log(output); output=""; } } pyramid()
If you want to print at the page, use like below 如果要在页面上打印,请使用如下所示
for (i = 0; i < 5; i++) {
let j=0;
do{document.write("*");j++;}while(j < i)
document.write("<br/>")
}
You can get rid of second for loop as follows: 您可以如下摆脱第二个for循环:
var str = ''; for (i = 1; i <= 5; i++) { str +=Array(i).join("*"); str +='\\n'; } console.log(str);
最短的代码:
console.log('*\\n**\\n***\\n****\\n*****');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.