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

118
Visualizações
Under what circumstances would it be useful to change a javascript array's length, without actually adding a new element

In this question, I figured out that my problem was because I had accidentally incremented the Array.Prototype.length property using ++

What I'm wondering is why length isn't a read-only property of Arrays? I see that it isn't an oversight in the language's design, because MDN says specifically it can "SET or return" the length of an array. I'm just wondering why I'm able to screw up in that particular way? What kind of use case would merit being able to change the length of an array without changing the number of elements it contains?

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

0

I found this interesting article from JavaScriptTutotorial.net that explains why you might use this.

Empty an array

If you set length to zero, the array will be empty:

const fruits = ['Apple', 'Orange', 'Strawberry'];
fruits.length = 0;

console.log(fruits); // []

Remove elements

If you set the length property of an array to a value that is lower than the highest index, all the elements whose index is greater than or equal to the new length are removed.

The following example changes the length property of the fruits array to two, which removes the third element from the array:

const fruits = ['Apple', 'Orange', 'Strawberry'];
fruits.length = 2;

console.log(fruits); // [ 'Apple', 'Orange' ]

Make array sparse

If you set the length property of an array to a value that is higher than the highest index, the array will be spare. For example:

const fruits = ['Apple', 'Orange', 'Strawberry'];
fruits.length = 5;

console.log(fruits); // [ 'Apple', 'Orange', 'Strawberry', <2 empty items> ]
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