I am starting on Javascript and I really have no idea how to put a linebreak into a variable:
I would like to build the following triangle without using print, just putting the result into a string :
Any idea ? Thanks
#
##
###
####
#####
######
var creerTriangle= function (taille) {
var triangle = "";
for (var i = 1; i <= taille; i++) {
var ligne = "";
for (var j=1; j <= (taille-i); j++) {
ligne+=(" ");
}
for (var k=1; k<=i; k++) {
ligne += "#";
}
triangle += ligne // how to put a linebreak here ?;
};
return triangle;
};
I think you just need "\\n". See where I've written <---
/* # ## ### #### ##### ###### */ var creerTriangle= function (taille) { var triangle = ""; for (var i = 1; i <= taille; i++) { var ligne = ""; for (var j=1; j <= (taille-i); j++) { ligne+=(" "); } for (var k=1; k<=i; k++) { ligne += "#"; } triangle += ligne +"\\n" //<--- }; return triangle; }; console.dir(creerTriangle(6));
For fun, here is another way to write this with ESNEXT:
const creerTriangle = tally => Array(tally) .fill() .map(() => '#'.repeat(tally)) .map((i, index) => i.replace(new RegExp(`#{${index}}`), ' '.repeat(index)) ) .reverse() .join('\\n') console.log(creerTriangle(6))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.