filter不会因undefined或null报错,但会跳过稀疏数组的空槽;对显式存入的undefined/null仍调用回调;安全过滤需用x != null等显式判断。

JavaScript 中 filter 方法本身不会因为数组里有 undefined 或 null 而报错,但它默认会跳过“空槽”(sparse array 的 holes),而对显式存入的 undefined、null 仍会传入回调函数处理。关键不是“空数组”,而是“含空值的数组”如何被过滤。
filter 对 undefined 和 null 的默认行为
filter 遍历的是数组的**自有可枚举属性索引**,不跳过 undefined 或 null 元素,只跳过真正缺失的索引(即稀疏数组中的 hole)。例如:
// 稀疏数组:索引 1 缺失 → filter 不会调用回调处理索引 1const arr1 = [1, , 3]; // [1, empty, 3]arr1.filter(x => console.log(x)); // 只打印 1 和 3,不打印任何东西对应空槽
// 密集数组:显式存入 undefined/null → filter 会传入它们const arr2 = [1, undefined, null, 4];arr2.filter(x => console.log(x)); // 打印 1 → undefined → null → 4
如何安全过滤掉 undefined 和 null
常用写法是显式判断,避免意外保留 falsy 值(如 0、false、''):
arr.filter(x => x !== undefined && x !== null)-
arr.filter(x => x != null)—— 利用null == undefined且二者都!=其他值(注意:这不是严格相等,但在此场景下安全) -
arr.filter(x => x === x && x != null)—— 排除NaN同时排除null/undefined(较少用)
注意:空数组 [] 本身没有问题
如果数组字面量就是 [],它不含任何元素(包括 undefined 或 null),filter 直接返回新空数组,无副作用:[].filter(x => x == null) // → [][].filter(x => console.log(x)) // 根本不执行回调
实用建议:统一预处理或封装工具函数
若项目中频繁需要剔除 null 和 undefined,可封装为复用函数:
立即学习“Java免费学习笔记(深入)”;
const compact = arr => arr.filter(x => x != null);compact([0, false, '', null, undefined, 'hello']); // → [0, false, '', 'hello']
如还需剔除所有 falsy 值(包括 0、false),则用 arr.filter(Boolean),但需确认业务是否允许。


















