JavaScript数组去重需明确null/undefined是否等价:用Set可区分二者并保序;手动遍历+includes兼容性好;若视为空值统一处理,需预判item==null并单独标记;禁用JSON.stringify或toString因语义错误。

JavaScript 中去重包含 null 和 undefined 的数组,关键在于明确“去重逻辑”:是否把 null 和 undefined 视为相同值?是否保留它们的原始顺序?是否需要兼容旧环境?下面提供几种常用、可靠的方法。
用 Set + 过滤(推荐:保留 null/undefined 且互不相等)
默认情况下,null !== undefined,所以多数场景下应把它们当作不同元素处理。此时可先用 filter 保留所有值(包括 null 和 undefined),再用 Set 去重:
-
Set能正确区分null、undefined和其他假值(如0、false、'') - 保持原始顺序,且不改变数据类型
示例:
const arr = [1, null, 'a', undefined, 1, null, 0, false, '', undefined]; const unique = [...new Set(arr)]; // → [1, null, 'a', undefined, 0, false, '']
手动遍历 + includes(兼容性好,显式控制)
如果需支持 IE 或想完全掌控比较逻辑(比如想把 null 和 undefined 合并为一个),可用传统循环:
立即学习“Java免费学习笔记(深入)”;
Java项目代码review工具。分析Git变更+完整调用链路上下文,推断业务需求,进行多维度评分和分类汇总,生成完整PRD文档。包含细粒度Java代码审查清单(Null安全、异常处理、Streams、并发、equals/hashCode、资源管理、API设计、性能、MyBatis/ORM、事务边界、SQL/DD...
- 用
includes()判断时,null和undefined不会互相匹配 - 若要合并二者,可改用
some()配合自定义判断(如item == null)
基础写法(区分 null/undefined):
const arr = [1, null, undefined, 1, null];
const unique = [];
for (const item of arr) {
if (!unique.includes(item)) unique.push(item);
}
// → [1, null, undefined]
按“空值统一处理”去重(null 和 undefined 当作同一类)
有时业务要求把 null 和 undefined 都视为“空”,只保留其中一个(通常是第一个出现的)。这时不能直接用 Set,需预处理:
- 将
null和undefined映射为统一占位符(如'__NULLISH__'),去重后再还原 - 或在遍历时用
item == null判断是否为空值,单独记录是否已存在空值
简洁实现:
const arr = [1, null, undefined, 'a', null, undefined];
const seenNullish = new Set();
const unique = [];
for (const item of arr) {
if (item == null) {
if (!seenNullish.has('nullish')) {
unique.push(item);
seenNullish.add('nullish');
}
} else {
if (!unique.includes(item)) unique.push(item);
}
}
// → [1, null, 'a']
注意:避免用 JSON.stringify 或 toString() 去重
这些方法容易出错:
-
JSON.stringify(null) === 'null',但JSON.stringify(undefined)是undefined(序列化后丢失) -
String(null) === 'null',String(undefined) === 'undefined',看似不同,但对象或数字可能误判(如{}和[]都转成'') - 对嵌套结构或函数无效,也不符合语义去重需求
除非你明确知道数据结构极其简单且无副作用,否则不建议。

















