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

154
Visualizações
When executing this code, instead of moving all items from 'myList' to 'myCart' it's exiting after moving just 3 of the items. Why?
let myList = ['pop tarts', 'ramen', 'chips', 'salsa', 'coffee']
let myCart = []


myList.forEach((item) => {
let poppedItem = myList.pop()
myCart.push(poppedItem)
console.log(myList)
console.log(myCart)
})

// When executing this code, instead of moving all items from 'myList' to 'myCart' it's exiting after moving just 3 of the items. I am totally lost as to why-

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

0

Try this

let myList = ['pop tarts', 'ramen', 'chips', 'salsa', 'coffee']
let myCart = Array.from(myList);
myList  = []
console.log(myList)
console.log(myCart)
about 4 years ago · Juan Pablo Isaza Relatório

0

The behaviour is expected because you are iterating over the array and in the same time you are modifying it.

  • Step 0 : item = 'pop tarts', 'coffee' is removed, myList = ['pop tarts', 'ramen', 'chips', 'salsa']
  • Step 1 : item = 'ramen', 'salsa' is removed, myList = ['pop tarts', 'ramen', 'chips']
  • Step 2 : item = 'chips', 'chips' is removed, myList = ['pop tarts', 'ramen']

You are already visited all the elements of the array so the forEach ends, for further informations you can check the mozilla documentation link I provided containing the modifying_the_array_during_iteration paragraph.

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