What you are trying to accomplish is rather simple. All you need is a for
loop that:
- iterates as many times as designated,
- uses
String.prototype.repeat
to create as many asterisks as the row number & - adds the newline character
"\n"
at the end of the string.
Example:
/* The function that creates the desired output for as many rows as given. */
function createOutput(rows) {
/* Create an empty string. */
var str = "";
/* Loop [rows] times and add [i] asterisks & a newline to the string each loop. */
for (var i = 1; i <= rows; str += "*".repeat(i) + "\n", i++);
/* Return the string. */
return str;
}
/* Create an output of 5 rows and log it in the console. */
console.log(createOutput(5));
Notes:
-
Since
String.prototype.repeat
was added in EcmaScript 6, it may not work for everyone. If you encounter that problem, you can supplant"*".repeat(i)
withArray(i+1).join("*")
. -
In order to include the above code in your application you have to:
-
save it in a file and load that using:
<script src = "https://stackoverflow.com/questions/49168597/file.js" type = "application/javascript"></script>
-
or paste it inside in your
HTML
file using:<script type = "application/javascript">[the code]</script>
.
-
solved Writing text expanding (pyramid) [closed]