Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

html - Exercise with a loop in javascript

I need for an university exercise to display onscreen with a document.write the tree below using a kind of loop:

tree

I used at the beginning a for loop but i printed only the first row... someone can help me?

This is what I tried:

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 
}

Thank You!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm going to give you a "golfed-ish" (goldfish? should this be a thing?) version of the code. In other words, the smallest, most obscure code I can think of to accomplish the task. You should not use this, because your teacher will undoubtedly ask you what it means and you won't know, but I'm bored 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>");

Demo

As I said, don't use this :p


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...