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

177
Visualizações
Why doesn't javascript reset the cursor back to zero after allocating a size to the array

Taken an array with given size, when we try to push the elements into it, javascript pushes the elements post the allocated size. Shouldn't javascript reset the cursor back to zero and push the elements from the 0th index onwards?

const arr = new Array(2);

arr.push(1);
arr.push(2);
arr.push(3);

console.log(arr.length);

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

0

When you create a new Array(2), it adds two elements, both with a value of undefined.

const arr = new Array(2);
console.log(arr); // [undefined, undefined]


When you add the extra three, it will just continue adding to the array, instead of deleting the last three.

const arr = new Array(2);

arr.push(1);
arr.push(2);
arr.push(3);

console.log(arr); // [undefined, undefined, 1, 2, 3]


If you, however, want to remove everything from the array, you can set length to 0.

const arr = new Array(2);

arr.length = 0;
console.log(arr); // []


In summary, JavaScript will keep adding elements unless you explicitly delete them.


Note: Don't use new Array(). Instead, use an empty array ([]). This answer used the Array() constructor to match with the question.

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