JSON.parse 的 reviver 返回 undefined,为什么字段直接消失了?
用设置恢复和数组空槽两个例子,说明 JSON.parse 的 reviver 如何处理返回值,以及如何排查字段被删除的问题。
从本地存储恢复设置时,updatedAt 读出来是字符串,往往还要转成 Date。如果加了一个日期转换回调,整份设置却变成 undefined,先检查日期以外的分支有没有返回值。这个回调还会收到整份设置对象。
漏掉 return,根对象也会丢
这个回调叫 reviver,按从里到外的顺序运行。它先处理属性值和数组元素,再处理包含它们的对象或数组。最后一次调用收到根值,参数 key 是空字符串。这次回调的返回值就是 JSON.parse 的结果。
const raw = '{"updatedAt":"2026-12-01T00:00:00Z","enabled":true,"slots":[3,null,8]}';
const broken = JSON.parse(raw, (key, value) => {
if (key === "updatedAt") return new Date(value);
});
const settings = JSON.parse(raw, (key, value) => {
if (key === "updatedAt") return new Date(value);
return value;
});
console.log("before", String(broken));
console.log("after", settings.updatedAt.toISOString());
console.log("enabled", settings.enabled);
console.log("slots", JSON.stringify(settings.slots));

第一版只有碰到日期字段才会返回值,其他分支都会走到函数末尾,得到 undefined。根对象也走了这条路径。第二版补上 return value,布尔值和数组就保留下来了。普通 JSON 属性也能叫 "",所以只看 key === "" 无法断定当前处理的是根值。
用的是同一份 JSON。补上返回值以前,String(broken) 是 "undefined"。补上以后,日期转成了 Date,enabled 仍是 true。写这类回调时,可以先把原样返回的路径留好,再写需要转换的字段。
数组元素删掉了,索引还在原位
再看一次有意删除属性的情况。这里让所有值为 null 的位置返回 undefined,其余值原样返回。对象少了一个 note 属性。数组删掉的是索引 1 的属性,所以这个位置留了个空槽,后面的值没有前移。
const source = '{"note":null,"slots":[3,null,8]}';
const data = JSON.parse(source, (key, value) => {
if (value === null) return undefined;
return value;
});
console.log("note own", Object.hasOwn(data, "note"));
console.log("slot 1 own", Object.hasOwn(data.slots, 1));
console.log("length", data.slots.length);
console.log("slot 2", data.slots[2]);
console.log("encoded", JSON.stringify(data.slots));
![预期控制台输出 note own false、slot 1 own false、length 3、slot 2 8、encoded [3,null,8]](https://img.javascript.cn/codex/articles/json-parse-reviver-undefined/reviver-console-180156d72721f5082e86.png)
预期输出里的两个 false 分别对应 note 和索引 1。Object.hasOwn(data.slots, 1) 查的是这个位置是否真的有属性。接着看长度和索引,数组长度还是 3,索引 2 读出来仍是 8。
空槽写回 JSON 仍然是 null
仅对比序列化字符串会掩盖内存结构的差异。原数组在索引 1 存了一个 null,处理后的数组在那里留了空槽。JSON.stringify 在这个例子里把两种情况都写成 null,因此数组的序列化结果都是 [3,null,8]。
![索引 1 从存在的 null 变成空槽,索引 0 和 2 保持原位,序列化仍写出 [3,null,8]](https://img.javascript.cn/codex/articles/json-parse-reviver-undefined/reviver-array-slots-1ac62bf3236e24784d27.png)
下标如果对应界面上的固定位置,保留 null 就能明确表达「这个位置没值」。如果想要一份连续的列表,可以正常解析,再对数组调用 filter(value => value !== null)。只需要转换某几个字段时,剩余分支记得返回原值。
JS数组push返回的是长度还是新数组?常见误用解析
2026-12-01
JavaScript原生Fetch调用SOAP WebService完整示例
2026-12-01
JS正则匹配汉字:一-龥范围局限与生僻字解决方案
2026-12-01
JS数组怎么获取指定元素的索引:indexOf与findIndex用法
2026-12-01
JS稀疏数组的length为什么大于实际元素个数
2026-12-01



