简体   繁体   English

javascript 中的循环树练习

[英]Tree exercise with a loop in javascript

I want to create a tree with *.我想用 *. I will give a number every time in order to specify the tree's height.我每次都会给出一个数字以指定树的高度。 It should look something like this if I give number 4 as height for example:如果我给数字 4 作为高度,它应该看起来像这样:

    *
   ***
  *****
 *******

I would like the tree to appear using console.log我希望树使用 console.log 出现

I have done that:我已经这样做了:

 var size = 4; document.write( "<center>" + Array.apply(0, new Array(size)).map(function(_, i) { return new Array((i + 1) * 2).join(" * "); }).join("<br>") + "</center>" );

but it doesn't work if I use console.log但如果我使用 console.log 它不起作用

You just need to count the spaces on the left per floor.您只需要计算每层左侧的空间。 The deepest one starts at j=0 .最深的从j=0开始。 The floor above at j=1 .上面j=1处的地板。 And so forth.等等。

Given a height h ,给定高度h

  • floor h-1->j=0楼层 h-1->j=0
  • floor h-2->j=1楼层 h-2->j=1
  • floor 0->j=h-1楼层 0->j=h-1

Notice that if you start at floor 0 , you get j=h-1 , and remove a space at every subsequent floor.请注意,如果您从楼层0开始,您将得到j=h-1 ,并在随后的每个楼层删除一个空间。

You can thus trivially write因此,您可以简单地编写

 const h = 4; console.log(Array(h).fill(0).map((_,i)=>{ return ' '.repeat(h-1-i)+'*'.repeat(i*2+1) }).join('\n'))

To clearify my comment.澄清我的评论。 You won't be able to show html in the console.您将无法在控制台中显示 html。 So you need to forget about tags.所以你需要忘记标签。 As when you are printing the tree you should know how big (height) it's going to be.当您打印树时,您应该知道它将有多大(高度)。 So you know how many spaces will preceed your star.所以你知道你的星星之前有多少个空格。

Number of spaces are given by the height in total - the current "level" from top to bottom - 1空格数由总高度给出 - 当前从上到下的“级别” - 1

and the number of stars is given by 2 times of the current "level" plus 1并且星数是当前“等级”的2倍加1

let spaces = " ".repeat(height-i-1);
let stars = "*".repeat(i*2+1);

So just use a loop to go through all the levels of the tree from top to bottom and concatinating the spaces and stars所以只需使用一个循环到 go 从上到下遍历树的所有级别并连接空格和星号

Here's an example on how that works (example also prints out to a textarea for preview purposes as well as in the console)这是一个关于它是如何工作的示例(示例还打印到文本区域以进行预览以及在控制台中)

https://codepen.io/relief_melone/pen/zYYRZmj https://codepen.io/relief_melone/pen/zYYRZmj

I created one like this.我创造了一个这样的。

function drawTree(height) {
        for ( let i = 0; i < height ; i++ ) {
            let star = '*';
            let space = ' ';

            for ( let j = 1; j <= i; j++ ) {
                star = star + '**';            
            }

            let gap = space.repeat(height-i-1);
            star = gap + star;
            console.log(star);
        }
    }

    let number = prompt('Give number for tree height');

    drawTree(number);

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

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