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