Reputation: 421
I am taking an intro to Javascript class and am stuck on an assignment.
Write a function called drawTriangle that returns the following string. Feel free to debug-print using console.log, but make sure that the function actually returns a string.
Note that in a string, the character for a carriage return (the equivalent of hitting the “Enter” or “Return” key) is “\n”.
#
##
###
####
#####
######
#######
My initial thought was that I would use a loop to populate an array (with the hope of finding a way to output the array as a string with line breaks) but I am stuck at that point and not sure how to move forward (or if I am going in the wrong direction).
My current script is as follows:
function triangle(number) {
var triElements = [];
var pound = '#';
var rightTriangle = '';
var lineBreak = '\n';
for (var i = 0; i < number; i++) {
var rightTriangle = rightTriangle.concat(pound)
triElements.push(rightTriangle);
}
return triElements;
}
console.log(triangle(6))
Upvotes: 2
Views: 818
Reputation: 2035
You are returning an array and not the triangle in a single string. I think you are over thinking it by using an array to store the result, just use a string like in this example:
function triangle(numOfLayers) {
var result = '';
var symbol = '#';
var layer = '';
var lineBreak = '\n';
for (var i = 0; i < numOfLayers; i++) {
layer += symbol; // add one symbol to last layer
result += layer + lineBreak; // append an extra line to the result
}
return result;
}
console.log(triangle(6))
Upvotes: 2