How to print a string s, n number of times using javascript?

var s= string;
var n =4; //dynamic
for (i = 0; i <= n; i++) {
        a.push(s);
        s= a.join(' ');
    }

this is the logic i am trying but it coming twice then i expected.

You’re pushing them on twice.

a.push(s) // you're pushing the string onto the array

Next you joining that array onto the string, which will then be pushed onto the array again on the next loop

s = a.join(' ') 

Move s = a.join(' ') out and do it at the end.

var s= 'x';
var n =4; //dynamic

for (i = 0; i <= n; i++) {
    a.push(s);
}

s= a.join(' ');

 
 
 
  …also don’t forget to define the variable “a”. :sunglasses:

<script>
(function() {
   'use strict';
   var s='x';
   var n=4; //dynamic
   var a=[];
for(var i=0;i<=n;i++) {
   a.push(s);
 }
   s=a.join(' ');
   console.log(a);
   console.log(s);
}());
</script>

coothead

thank you all

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.