Home > Blockchain >  How to use padStart in a JS loop to output a triangle of Xs?
How to use padStart in a JS loop to output a triangle of Xs?

Time:07-16

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.

CodePudding user response:

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

So you can add it to a loop and just pass it an empty string so it will always have 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>

CodePudding user response:

You'll have to collect output lines in the loop somehow. But your use of padStart is also wrong: the first argument should not be a string, but a number. It should actually 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 method repeat 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>

  • Related