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

120
Visualizações
Why an empty array of N length in javascript does not have indices?

So I have created an empty array in Javascript

const x = Array(5);

Or

const x = new Array(5);

And if i check the length, Its 5 in both the cases but when I loop over it using .map then it did not give me the indices i.e 0,1,2,3,4

x.map((el, i) => i);

This should return [0,1,2,3,4]

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

0

Because the specification requires that when an array is created like that with the Array constructor, where values is the argument list:

a. Let len be values[0].
b. Let array be ! ArrayCreate(0, proto).
c. If Type(len) is not Number, then
  i. Perform ! CreateDataPropertyOrThrow(array, "0", len).
  ii. Let intLen be 1𝔽.
d. Else,
  i. Let intLen be ! ToUint32(len).
  ii. If SameValueZero(intLen, len) is false, throw a RangeError exception.
e. Perform ! Set(array, "length", intLen, true).
f. Return array.

That's all it does, and nothing else. In short, it creates a new array object inheriting from Array.prototype, and then sets a length property on it. It doesn't create any numeric indicies on the array.

It's like

const createArray = (length) => {
  const newArr = Object.create(Array.prototype);
  newArr.length = length;
  return newArr;
};

const arr = createArray(5);
console.log(arr.length);
console.log(arr.hasOwnProperty('0'));

As a result, if you want to iterate over the array, you'll have to fill it first somehow - either with .fill, Array.from, or spreading it into a new array..

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