Reputation: 36
I'm looking for feedback/insight on using console.log
instead of document.write
to solve the looping triangle with a space in the CS50 Mario style problem.
Triangle loop - CS50 mario style
var str = "#";
var height = 8;
for (var i = 0; i < height; i++) {
for (var j = 0; j < height-i-1; j++) {
document.write("_");
}
{
for (var k = 0; k < i + 2; k++) {
document.write(str);
}
document.write("<br />");
}
}
//
_______##
______###
_____####
____#####
___######
__#######
_########
#########
The document.write(“_”)
is because the DOM trims any white space so (“ “)
won't work - took me ages to figure that out.
I can’t get the triangle to come out right aligned using console.log()
instead of document.write
- any thoughts?
Cheers - I'm a huge SOF fan for learning.
Upvotes: 1
Views: 91
Reputation: 1187
The reason console.log
is not working for you is because console.log
auto changes lines. So if you want to use console.log
version, switch to the below version:
var str = "#";
var height = 8;
for (var i = 0; i < height; i++)
{
var line = "";
for (var j = 0; j < height-i-1; j++) {
line += " ";
}
for (var k = 0; k < i + 2; k++) {
line += str;
}
console.log(line);
}
Tested working with node.
Upvotes: 1