什么是最好的方式来迭代在JavaScript中迭代期间增长的数组?我想迭代所有添加的元素,甚至在迭代期间添加的元素。我想在功能性编程风格上做到这一点。函数式编程风格增长数组循环
例如看到这个代码执行了
let a = [
\t 'x',
'y'
]
let limit = 4 // limit the test
for (let i=0; i<a.length; i++) {
\t console.log(a[i])
limit--
if(limit>0){
a.push(a[i]+'-')
}
}
console.log(a)
后
[
"x",
"y",
"x-",
"y-",
"x--"
]
但是,如果我尝试用另一种 “funcional” 模式一样的forEach新增加的元素未印刷
let a = [
\t 'x',
'y'
]
let limit = 4 // limit the test
a.forEach((e) => {
console.log(e)
limit--
if(limit>0){
a.push(e+'-')
}
})
console.log(a)
第一回路检查长度每次迭代。随着长度的增长迭代继续。使用'forEach()'只能迭代原始数组长度 – charlietfl
a.forEach((e))说:对于每个元素,名为e,do:/:你的代码,这不是范围 –
_“什么是最聪明的如何迭代在迭代过程中增长的数组?在迭代过程中,JavaScript?“_从功能角度来看:迭代不增长的数组。 – ftor