Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

298
Vistas
String is returning empty line after every input

I've been trying to figure this out for a while but have run out of possible solutions. This is for a school assignment that is meant to create a "triangle" based on the number inputted (so if I put 3, the first line will have 1 asterisk, the second will have 2, and the third 3). The code is running fine but I'm getting an extra empty line because of the "\n" and am unsure how to remove it. My code:

function drawTriangle(size) {
   let string = "";    //declares a variable string
   for (let i = 1; i <= size; i++) {  //loop continues upto size
       for (let j = 0; j < i; j++) {  //loop starts from 0 and ends at i
         string += "*";   //* is added to string
       }
       string += "\n";  //when 1 row is finished, next line is printed on new line
     }
     console.log(string);  //outputs the string to the console
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As per Bergi's comment, create a local array variable and add line break at the end by using .join("/n").

Live Demo :

function drawTriangle(size) {
  let str = '';    //declares a variable string
  const arr = [];
  for (let i = 1; i <= size; i++) {  //loop continues upto size
    for (let j = 0; j < i; j++) {  //loop starts from 0 and ends at i
      str += "*";   //* is added to string
    }
    arr.push(str);
    str = '';
  }
  return arr
};

const result = drawTriangle(3).join("\n");

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda