JavaScript中map遍历含null/空元素的数组及null值替换方法
问题原因
- JavaScript 中的
Array.prototype.map()方法遍历数组时,会自动跳过稀疏数组的空槽(即未显式赋值的索引位置),不会为这些空槽执行回调逻辑。 - 你看到的
null大概率是控制台打印稀疏数组时的展示效果,实际这些位置是空槽,没有触发你的map回调,自然不会执行替换逻辑。你可以通过e.hasOwnProperty(对应索引)验证,空槽对应索引会返回false,显式赋值为null的位置会返回true。
解决方案
方案1:用Array.from()把稀疏数组转为普通数组
Array.from()会将数组空槽自动转为undefined,之后再用map遍历就能覆盖所有位置,修改后的代码如下:
let output = { data: sheet.map((e) => { return Array.from(e).map((f) => { console.log('f: ', f); if (f === null || f === undefined) { return { value: '' }; } return f; }); }), positionCells: positionCells, };
方案2:用普通for循环遍历所有索引
手动遍历数组全部索引,不需要处理空槽:
let output = { data: sheet.map((e) => { const processed = []; for (let i = 0; i < e.length; i++) { const f = e[i]; console.log('f: ', f); processed[i] = f === null || f === undefined ? { value: '' } : f; } return processed; }), positionCells: positionCells, };
内容的提问来源于stack exchange,提问作者codecustard
相关产品推荐
相关产品推荐

