1

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;
};
4
  • add an \n or br? Commented Feb 12, 2018 at 19:47
  • "\n" is the new line character, where are you placing this text on your web page, because depending on the element type, it may not work with newline Commented Feb 12, 2018 at 19:47
  • Just triangle += ligne + '\n' Commented Feb 12, 2018 at 19:51
  • that's right. Forgot I had to print the function print(creerTriangle(n)) instead of just creerTriangle(n), for it to print the triangle. Many thanks ! Commented Feb 12, 2018 at 20:04

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

that's right. Forgot I had to print the function print(creerTriangle(n)) instead of just creerTriangle(n), for it to print the triangle. Many thanks !
0

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))

https://repl.it/@ryanpcmcquen/javascriptCreateTriangle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.