javascript - 为什么 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
解决方案
您正在修改您的数组,同时迭代它。相反,您应该像这样使用它的副本:
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)
}
推荐阅读
- maven - 在eclipse中使用tomcat9作为部署服务器作为插件
- python - PyPI bezier 0.8.0:绘制平滑贝塞尔曲线所需的最少点数?
- messagebroker - 在消息代理计算节点上使用 ESQL 进行 xml 到 xml 字段属性转换
- ios - 当 Firebase 查询限制超过 9 时 iOS 应用程序崩溃
- python - 从python 3中的列表中删除特定元素
- api - 列出 Jenkins 下的所有文件夹及其路径
- php - 输出一个 var 和一个回显的测试结果?
- ruby-on-rails - 使用相同代码的 2 个测试之间的 Rspec 不一致结果
- java - 无法跨活动访问全局变量
- database - 如何命名包含受限字符的列,以便该名称直观?