JavaScript中forEach遍历Array构造数组的异常行为及方案问询
首先要明确:forEach和map这两个方法的原生实现逻辑就是会跳过数组里的空槽,也就是Array(n)生成的那种仅设置了length属性、没有实际初始化索引位的数组元素,所以只要你用这两个方法,又不把空槽填充成实际值(哪怕是值为undefined的元素),它们肯定不会遍历到空槽位置,这是ECMAScript规范明确规定的行为,没有例外。
你目前用到的扩展运算符、fill()都是把空槽转成实际undefined元素的方案,除此之外还有以下常用实现:
1. 用Array.from生成可迭代数组
Array.from接收长度为n的空槽数组时,会自动把所有空槽转成undefined值,语法简洁:
// 生成的数组已经没有空槽,forEach/map都可以正常遍历 const undefinedArray = Array.from(Array(3))
如果你的最终目标是直接生成带索引的模拟数据,还可以直接用Array.from的第二个回调参数,省掉单独的map/forEach步骤:
// 直接生成id从0到2的对象数组 const mockData = Array.from(Array(3), (_, id) => ({ id })) // 要转成字典也可以一步到位 const dictionary = Object.fromEntries(mockData.map(item => [item.id, item]))
2. 换用其他不跳过空槽的遍历方式
如果不想修改原空槽数组,可以直接不用forEach/map,换用不会跳空槽的遍历语法:
- 普通for循环,直接按length遍历索引即可:
const undefinedArray = Array(3) const dictionary = {} for (let i = 0; i < undefinedArray.length; i++) { console.log('Logging at index: ', i) const someObject = { id: i }; if (!dictionary[someObject.id]) { dictionary[someObject.id] = someObject } }
- 用
keys()方法遍历数组索引,空槽数组的keys迭代器会返回所有合法索引:
const undefinedArray = Array(3) const dictionary = {} for (const index of undefinedArray.keys()) { console.log('Logging at index: ', index) const someObject = { id: index }; if (!dictionary[someObject.id]) { dictionary[someObject.id] = someObject } }
for...of循环也不会跳过空槽,遍历时空槽会被识别为undefined值:
const undefinedArray = Array(3) const dictionary = {} let index = 0 for (const _ of undefinedArray) { console.log('Logging at index: ', index) const someObject = { id: index }; if (!dictionary[someObject.id]) { dictionary[someObject.id] = someObject } index++ }
内容的提问来源于stack exchange,提问作者jrend
相关产品推荐
相关产品推荐

