How to mount a number 1 pyramid of 20 consecutive lines?

Asked

Viewed 64 times

0

I have the code:

let i = 0

for(i = 0; i<= 20; i++){
    const p  = 1**i
    console.log(p)
}

And I expect a way out like:

1
11
111
1111
11111
111111
1111111
11111111

But I’m failing to create this form of "pyramid".

2 answers

6


One option that I consider a little more appropriate for this sort of thing is to use the method String.prototype.repeat, repeating a string N times.

for (let i = 1; i <= 10; i++) {
  console.log('1'.repeat(i));
}

Note that this method was introduced in the Ecmascript 2015 (ES6) specification. Although the support is currently very high - 94,5% at the time I write this -, it is worth consulting a compatibility table before using it. You can use a polyfill to circumvent possible lack of support. The same care of use should be taken with the declarations let and const.

  • 1

    Good. I saw this option, but preferred the "old javascript". + 1

  • 1

    Note : This blessed function does not work in Internet Explorer.

  • Thanks for the remark, @Wallacemaxters! :-)

  • 1

    Good observation on the let. Since I’m using the "old" version, I changed my answer to var.

  • 1

    I did not know this option of repeat, thank you for enlightening me

2

As a matter of fact, you wish it?

for (var i = 0; i <= 20; i++) {

    var p = Array(i + 1).join('1');

    console.log(p);
}

The function Array, when added a number, it will generate an array with empty items, according to that amount passed.

Example:

console.log(Array(5))

console.log(Array(2))

console.log(Array(10))

The function join in turn, it will join this entire array using the number '1' like "glue".

Behold:

console.log(Array(4).join('1'))

console.log(Array(7).join('5'))

console.log(Array(10).join('$'))

  • 1

    solved my problem very grateful for the attention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.