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

Viewed 37

my wrong example:

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

I am trying to get: ['1234', '12340', '123400', '1234000', '1234000', '123400000', '1234000000']

3 Answers

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);

FYI, instead of for loop, you can use a while loop to make your code cleaner:

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

console.log(array);

let array  = [];
let prefix = "1234";
for(let n=0; n<7; n++){
  let new_value = prefix;
  for(let i=0;i<n;i++){
    new_value += "0";
  }
  array.push(new_value);
}
console.log(array);
Related