• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

89
Views
¿Por qué forEach no recorrerá toda la matriz?

Cuando solo uso console.log() dentro del método forEach, registra todos los elementos de Array, pero cuando uso .push(array.pop()) dentro de él, ¿se detiene en algunos de los elementos?

 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" // ]

pero aquí funciona

 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
almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Está modificando su matriz mientras itera a través de ella. En su lugar, debe usar una copia así:

 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) })

O, como no necesita elementos en la devolución de llamada, debe usar simple for loop

 const count = array.length for (let i=0; i < count i++) { newArray.push(array.pop()) console.log(arr) }
almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error