how do I make an array that contains strings of numbers with x length in javascript?

my wrong example:

var prefix = '1234';
for (var x = 4; x<= 10; x++) 
  if (prefix.length !== x) {
  prefix.concat('0')
  }

what im trying to get: [‘1234’, ‘12340’, ‘123400’, ‘1234000’, ‘1234000’, ‘123400000’, ‘1234000000’]

25 thoughts on “how do I make an array that contains strings of numbers with x length in javascript?”

  1. You need to reassign the new value to the variable; concat does not modify the string.

    const res = [];
    var prefix = '1234';
    for (var x = 4; x <= 10; x++) {
      res.push(prefix);
      prefix = prefix.concat('0');
    }
    console.log(res);

    You could also use Array.from along with String#repeat.

    const prefix = '1234';
    const res = Array.from({length: 7}, (_,i)=>prefix+'0'.repeat(i));
    console.log(res);
    Reply
  2. FYI, instead of for loop, you can use a while loop instead to make your code cleaner:

    var prefix = '1234';
    var array = [];
    while (prefix.length <= 10) {
      array.push(prefix);
      prefix += '0';
    }
    
    console.log(array);
    Reply

Leave a Comment