繁体   English   中英

在 javascript 中使用循环练习

[英]Exercise with a loop in javascript

我需要一个大学练习来在屏幕上显示一个文档。使用一种循环编写下面的树:

树

我在开始时使用了 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 
}

谢谢你!

我会给你一个“golfed-ish”(金鱼?这是一个东西吗?)版本的代码。 换句话说,我能想到的最小、最晦涩的代码来完成任务。 不应该用这个,因为你的老师肯定会问你这是什么意思,你不会知道,但我很无聊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

这是我给你的代码......

<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>

 <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:注意魔术数字

添加空格和完全可扩展

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, '*') );

小提琴

 function pyramidStar(n) { var str = ""; for(var i=1; i<=n; i++) { for(var j=1; j<=ni; 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);
 <pre id="result"></pre>

另一种打印星星金字塔的方法。

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM