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

108
Visualizações
Why forEach won't loop through the entire Array?

When I only use console.log() inside the forEach method it logs all the Array elements, but when I use the .push(array.pop()) inside it, it stops at some of the elements?

const sentence = ['sense.','make', 'all', 'will', 'This'];

function reverseArray(array) {
   debugger;
   let newArray = [];

   array.forEach((arr) => {
     newArray.push(array.pop())
     console.log(arr) 
   })

  return newArray;
}

console.log(reverseArray(sentence))
// RESULT [
//  "This",
//  "will",
//  "all"
// ]

But here it works

const sentence = ['sense.','make', 'all', 'will', 'This'];

function reverseArray(array) {
   debugger;

   array.forEach((arr) => {
     console.log(arr) 
   })
}

reverseArray(sentence)
// Now it works
// RESULT
// sense.
// VM94:7 make
// VM94:7 all
// VM94:7 will
// VM94:7 This
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are modifying your array while iterating through it. Instead You should use copy of it like so:

Array.from(array).forEach((elm) => {
  newArray.push(array.pop())
  console.log(elm)
})

// another variant for old browsers

array.slice().forEach((elm) => {
  newArray.push(array.pop())
  console.log(elm)
})

Or, as you do not need elements in callback, you should use simple for loop

const count = array.length
for (let i=0; i < count i++) {
   newArray.push(array.pop())
   console.log(arr) 
}
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