我需要大学练习在屏幕上显示一个文档。使用一种循环写下面的树:
我在开始时使用for循环,但我只打印了第一行......有人可以帮我吗?
这就是我的尝试:
var numbers = [0, 1, 2, 3, 4]
for (var i = 0; i <= numbers.length; i++) {
if (numbers [i] == 0) {
document.write(" * </br>");
}
if (numbers [i] == 1) {
document.write(" *** </br>");
}
if (numbers [i] == 2) {
document.write(" ****** </br>");
}
if (numbers [i] == 3) {
document.write(" ******* </br>"); }
if (numbers [i] == 4) {
document.write("********* </br>");
}
return
}
谢谢!
答案 0 :(得分:3)
我打算给你一个&#34;高尔夫球运动&#34; (金鱼?这应该是什么?)代码的版本。换句话说,我能想到的最小,最模糊的代码来完成任务。你不应该使用这个,因为你的老师无疑会问你这意味着什么,你不会知道,但我很无聊XD
var size = 5;
document.write("<center>"+Array.apply(0,new Array(size)).map(function(_,i) {return new Array((i+1)*2).join(" * ");}).join("<br>")+"</center>");
正如我所说,不要使用它:p
答案 1 :(得分:1)
这是我的代码......
<html>
<head>
<script type="text/javascript" language="javascript">
document.write("<center>"); //write a center tag to make sure the pyramid displays correctly(try it without this step to see what happens)
for(var i = 0; i <= 10; i++) //a loop, this counts from 0 to 10 (how many rows of stars)
{
for(var x = 0; x <= i; x++)// a loop, counting from 0 to whatever value i is currently on
{
document.write("*");//write a * character
}
document.write("<br/>"); //write a br tag, meaning new line, after every star in the row has been created
}
document.write("</center>"); //close the center tag, opened at the beginning
</script>
</head>
<body>
</body>
</html>
答案 2 :(得分:1)
<pre><script>
for(var i=0;i<5;i++)
{
for(var c=0;c<9;c++)
{
if(Math.abs(4-c)<=i)
document.write("*");
else
document.write(" ");
}
document.write("<br />");
}
</script></pre>
这是一个带document.write()的简单版本。唯一复杂的是Math.abs,它给出了距离中间的距离。
PS:注意魔术数字
答案 3 :(得分:1)
添加空格和完全可扩展的
function pyramid(lines, char) {
var start = 2,html = '<pre>';
for (var i=lines; i--;) {
html += new Array(Math.floor(i+1)).join(' ') + new Array((start=start+2)-2).join(char) + '<br />';
}
return html + '</pre>';
}
document.write( pyramid(5, '*') );
答案 4 :(得分:1)
function pyramidStar(n) {
var str = "";
for(var i=1; i<=n; i++) {
for(var j=1; j<=n-i; j++) {
str += " ";
}
for(var k=n-i+1; k<n+i; k++) {
str += "* ";
}
for(var m=n+i; m<=2*n-1; m++) {
str += " ";
}
str += "\n";
}
return str;
}
document.getElementById("result").innerHTML = pyramidStar(9);
&#13;
<pre id="result"></pre>
&#13;
印刷金字塔的另一种方式。
答案 5 :(得分:0)
function star(n) {
for (var i = 1; i <= n; i++) {
for (var j = i; j < n; j++) {
document.write("-");
}
for (var k = 1; k <= (2 * i) - 1; k++) {
document.write("*");
}
document.write("<br/>");
}
}
//函数调用
星(9);