How to draw such a triangle on javascript?

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

I would appreciate if you explain how it works.

So far I have such a code:

 var lines = 7; var str = " "; var star = "*"; for(var i = 0; i < lines; i++){ str += star; console.log(str); } 
  • First print only the first line: 4 spaces and one asterisk. Show your code. - Sergiks
  • var lines = 7; var str = ""; var star = "*"; for (var i = 0; i <lines; i ++) {str + = star; console.log (str); } - Ashot
  • Leave as long as the search in rows. Print only the very first line of this triangle: 4 spaces, 1 asterisk, again 4 spaces. - Sergiks
  • I only understand the logic, but I cannot realize it) - Ashot
  • 2
    You can always write console.log ('*') for each line of your own - that's the triangle, in principle:) And then, like a cool programmer, you want to “optimize” this work. - Sergiks

6 answers 6

For example:

 var i = 0, j = 0; // Желаемое количество строк var max = 15; var space = "", star = ""; while (i < max) { space = ""; star = ""; for (j = 0; j < max - i; j++) space += " "; for (j = 0; j < 2 * i + 1; j++) star += "*"; console.log(space + star); i++; } 
  • I first wrote let, because let would work only inside the context for. This is a habit in this case) - Vasily Barbashev
  • @Sergiks Done - Vasily Barbashev
  • Thank! For perfectionism, maybe, all the variables in one var set? - Sergiks
  • Well, the variables for the cycle in their var, the program settings in their own, and the temporary variables in their own, everything seems fine, every perfectionist will find his own beauty here) - Vasily Barbashev

And here's another way:

 var lines = line = 5, a='.', b='*'; while(line-->0) console.log(Array(line+1).join(a) +Array(2*(lines-line)).join(b) +Array(line+1).join(a)); 

It turns out:

 ....*.... ...***... ..*****.. .*******. ********* 

How it works:

The while decreases the line variable by 1 and is executed while it is (before decreasing, because the “-” after the variable) is greater than 0 . With an initial value of 5 , inside the loop, the line takes the value 4,3,2,1,0

We display the next line in the console: console.log()

The argument in it is the sum of three lines: something before the asterisks, asterisks, and something after them (if we only output asterisks and spaces, then the third part “after them” is not needed).

Spaces to the stars. They need as much as the value of the variable line . For example, for the first line, line=4 and spaces are needed. 4. For the last line, 0 and 0.

To get N characters in a row, you can use this trick: create an empty array of N+1 elements, and “glue” it using our symbol as a separator. For example, an array of three elements [1,2,3] , gluing the separator ":", we get:

 [1,2,3].join(":") // "1:2:3" 

And if the array consists of empty elements, then as a result there will be a string consisting only of delimiters:

 Array(3).join(":") // "::" 

So, line spaces will give the expression Array(line+1).join(" ") .

Stars. The number of stars begins with 1 and increases in steps of two: 1,3,5 . And for the trick with .join() will need another one more: 2,4,6.. It is necessary from a series of 4,3,2,1,0 to get 2,4,6,8,10 . Because line decreases, but you need to increase, probably, the line should be taken with the sign "-": -4, -3, -2 . “Lift” by adding the initial lines : lines-line = 1,2,3.. and making the rise more abruptly, multiplying by 2: 2,4,6.. - what you need. Total, the expression of the number of elements in the array for the stars: (lines-line)*2 , and the stars in the line will be: Array((lines - line) * 2)

You can design it as a function like this:

 /** * Возвращает массив строк для рисования ёлки * * @param int n число строк * @param string optional символ для заполнения левее дерева, по умолчанию пробел * @param string optional символ дерева, по умолчанию звёздочка * @param string optional символ правее дерева, по умолчанию пробел * * @return array массив строк */ function elka(n) { var prefix = arguments.length > 1 ? arguments[1] : ' ' ,star = arguments.length > 2 ? arguments[2] : '*' ,suffix = arguments.length > 3 ? arguments[3] : ' ' ,line = n ,result = [] ; while(line-- > 0) { result.push( Array(line + 1).join(prefix) + Array((n - line) * 2).join(star) + Array(line + 1).join(suffix) ); } return result; } // вывод в консоль elka(5).map( function(el){ console.log(el)}); // вывод в HTML документ document.body.innerHTML = '<pre>' + elka(4,'_','X','_').join("<br>\n") + '</pre>'; 

  • The first option is probably better)) and thanks all the same - Ashot

Here is my example, this triangle displays:

  * * * * * * * * * *********** var w = 25; var h = (w - (w % 2)) / 2 + (w % 2); var spaces = w; for (i = h; i > 0; i--) { var str = ""; for (j = i; j <= w; j++) { if (i === 1) { str += "*"; } else if (j === w || j === spaces) { str += "*"; } else { str += "&nbsp&nbsp"; } } spaces -= 2; document.write(str + "<br/>"); } 
     var n = "&nbsp" for(let i = 0; i < 8; i++){ for(let k = 8; k > i - 1; k--){ document.write(n,n) } for(let j = 0; j < i + 1; j++){ document.write("*",n,n) } document.write("<br>") } 
       var lines=5; var star=1; var space=15; for(var i=0;i<lines;i++){ for(let j=0;j<space;j++){document.write("&nbsp;")} for(let j=0;j<star;j++){document.write('<b>*</b>')} star+=2; space--; document.write("<br>"); } 
          var line = 5; // Quantity of lines var space = 4; // Quantity of gaps in the first line var star = 1; // Quantity of stars in the first line for (var h = 0; h < line; h++) { for (var wsp = 0; wsp < space; wsp++) { document.write("&nbsp\n"); } for (var wst = 0; wst < star; wst++) { document.write("*"); } space -= 1; star += 2; document.write("<br>"); }