Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

139
Vistas
How to use padStart in a JS loop to output a triangle of Xs?

I am supposed to create a triangle of Xs as depicted in the link by using padString image of 20 lines of Xs starting with one X and incrementing by one X for each additional line

The hint they gave was that I am supposed to use something like...

let str = "";
str = str.padStart(i,”x”); // i is the loop counter

What I have so far is this...

let xShape = "x";
for (let counter = 0; counter <= 20; counter = counter + 1) {
  xShape = xShape + "x"
}
document.getElementById("demo").innerHTML =
  xShape.padStart(xShape, "x");
<p id="demo"></p>

But that doesn't write out 20 lines of Xs starting with the first line having only one X with each new line having an additional X. It only writes the last line of 20 Xs. How do I get it to write all 20 lines? I am a beginner, and am doing this to learn. Thank you so much for your help.

7 months ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

padStart takes the string passed to it and pads the beginning with the first argument as many times as the second argument.

Then you can add it to a loop and just pass it an empty string so it always has an empty starting point.

 let xShape = ""; for (let counter = 0; counter <= 20; counter++) { xShape += "".padStart(counter, "x") + "<br>"; } document.getElementById("demo").innerHTML = xShape;
 <div id="demo"></div>

7 months ago · Santiago Gelvez Denunciar

0

You'll have to collect output lines in the loop somehow. But your use of padStart is also wrong: the first argument must not be a string, but a number. Actually it should be your loop counter.

 let lines = []; for (let counter = 1; counter <= 20; counter = counter + 1) { lines.push("".padStart(counter, "x")); } document.getElementById("demo").innerHTML = lines.join("<br>");
 <p id="demo"></p>

Note that the repeat method is more natural here:

 let lines = []; for (let counter = 1; counter <= 20; counter = counter + 1) { lines.push("x".repeat(counter)); } document.getElementById("demo").innerHTML = lines.join("<br>");
 <p id="demo"></p>

In a more functional approach:

 document.getElementById("demo").innerHTML = Array.from({length:20}, (_, counter) => "x".repeat(counter+1)) .join("<br>");
 <p id="demo"></p>

7 months ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos