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

144
Visualizações
Why is Array.map returning different results?

According to my current JS understanding, All 3 lines below should return the same result, can someone please explain what I'm missing ?

1- Unexpected

[...Array(6).map((x) => 1)]
(6) [undefined, undefined, undefined, undefined, undefined, undefined]

2- expected

[...Array(6)].map((x) => 1)
(6) [1, 1, 1, 1, 1, 1]

3- unexpected

Array(6).map((x) => 1)
(6) [empty × 6]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Array(n) creates an array of length n, but the array has no values in it so there is nothing to map over.

Basically, this:

const a = Array(n);

is the same as:

const a = [];
a.length = n;

This is why the created array has no elements in it. Attempting to map it will do nothing since there are no values to map.

You can, however, convert that empty array to an array of undefined values. This can be done in two ways:

One is using the spread operator as you have done:

[...Array(n)] // creates new array [undefined, undefined, undefined ...] n times

The other, more commonly used, is .fill(), which sets its parameter as the value for all the indices of the array. To fill with undefined, do:

Array(n).fill() // fills array with [undefined, undefined, undefined ...] n times

An array of undefined, unlike an empty array, has elements and can therefore be mapped:

[undefined, undefined, undefined].map(x => 1) // [1, 1, 1]

So you can first convert your empty array to an array of undefined, and then map it like so:

Array(n).fill().map(x => 1)

If you want to fill the array with the same element in each position like in this example, you can simply pass it in to fill without needing to map the array:

Array(n).fill(1)
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