首页 > 解决方案 > 为什么 forEach 不会遍历整个数组?

问题描述

当我只在 forEach 方法中使用 console.log() 时,它会记录所有 Array 元素,但是当我在其中使用 .push(array.pop()) 时,它会在某些元素处停止?

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

但在这里有效

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

标签: javascriptarrays

解决方案


您正在修改您的数组,同时迭代它。相反,您应该像这样使用它的副本:

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

或者,由于您不需要回调中的元素,您应该使用简单for循环

const count = array.length
for (let i=0; i < count i++) {
   newArray.push(array.pop())
   console.log(arr) 
}

推荐阅读