Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda