Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
Create N length of array with values

I am creating a N length array with value filled in, I am looking if I can improve the way I am doing it.

I get random number on the fly to determine the number of array item.

What I am doing is:

For example, if the number is 5.

let array = [];

for (let i = 1; i <= 5; i++) {
  array.push(`item0${i}`)
}

Now, the array will be ['item01', 'item02, .... 'item05']

This looks quite long, can this be done is a shorter way?

Thanks

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Simply use the new Array Constructor.

const arr = new Array(5)

This however will only create an array of length 5 without any entries. To use array methods on the array, you will first have to either fill the array with valus, or create entries of value undefined using the spread syntax.

If you want to pre-populate the array:

function makeArray(n) {
    return (new Array(n)).fill().map((el,ind) => `item0${ind}`)
}

makeArray(5);

Or even provide a callback as property so you can change what the pre-filled elements look like and use spread syntax to avoid the .fill() call:

function makeArray(n, cb) {
    return [...new Array(n)].map((el,ind) => cb(ind))
}

makeArray(5, (ind) => `item0${ind}`);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda