Warm tip: This article is reproduced from serverfault.com, please click

returning a triangle

发布于 2020-11-27 10:28:12

I am trying to write a function to return a reverse right triangle but I am having trouble figuring out where I am going wrong.

function triangle(num) {
  let star = ""
  for (let i = num; i >= 1; i--) {
    for (let j = num; j >= 1; j--) {
      star += "*" + "\n"
    }
  }
  return star
}

console.log(triangle(6));

My problem is I am having trouble getting the whole function to return a string of * in the form of a reverse triangle. I believe I have concocted the '\n' in the wrong place as well but I am not sure where to change it to.

I am receiving back this:

console.log(triangle(6));    
************************************

I am supposed to receive back this:

console.log(triangle(6));
"******\n*****\n****\n***\n**\n*"

I am supposed to concatenate \n to the string output.

-THIS IS WHERE I AM HAVING THE PROBLEM-

Questioner
andy86
Viewed
0
Bjørn Nyborg 2020-11-27 22:20:04

I think this is what you want:

function triangle(num) {
  let star = ""
  for (let i = num; i >= 1; i--) {
    for(let j = i; j >= 1; j--) {
       star += "*"
    }
    if(i !== 1) {
      star += "\\n"
    }
  } 
  return star 
}

console.log(triangle(6));

See example here: https://codepen.io/bj-rn-nyborg/pen/gOwOdxR

I moved the +"\n" to the outer loop, and also initialized let j = i instead num