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

82
Visualizações
Destructuring array elements inside the for loop in javascript

Let's assume that I have a code structure as below,

const fruits = [ `apple`, `banana`, `orange` ];

for ( let i = 0; i < fruits.length; i++ ) {

    const res = fruits[ i ];
    console.log ( res ); // apple banana orange
}

I want to destructure the

const res = fruits[ i ];

Is it possible and I can use forEach to achieve the destructuring but I want to achieve the same using the for loop.

Thanks in advance.

PS: using forEach or for..in it can be done but I want to get same destructuring within the for loop.

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

0

If you absolutely want to keep the classic for loop:

const fruits = [`apple`, `banana`, `orange`];

for (let i = 0; i < fruits.length; i++) {
    const { [i]: res } = fruits;
    console.log(res); // apple banana orange
}

As a shorter syntax, for..of works with iterable objects (like arrays).

You can use it like this:

const fruits = [`apple`, `banana`, `orange`];

for (const fruit of fruits) {
    console.log(fruit); // apple banana orange
}

To go further, you can even use destructuring in a for..of loop (e.g: to retrieve the string lengths):

const fruits = [`apple`, `banana`, `orange`];

for (const { length } of fruits) {
    console.log(length); // 5 6 6
}

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