← 中文资源

简体中文版本

JSON.stringify 静默丢弃 undefined

undefined 字段、函数与 symbol 在序列化时直接消失,数组槽位写成 null 而对象键整个丢掉:还原后这些字段不复存在。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

stringified: {"id":7,"tags":["a",null,"b"]}
restored keys: [ 'id', 'tags' ]
array hole became: null
array keeps slot as null: ["x",null]
object drops the key: {}

实现说明

各个操作都建立在顶层绑定之上:payload、json、restored。

使用要点

  • 演示输出是带标签的(stringified:、restored keys:、array hole became:),每个操作都会留下自己的一行标注。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件的状态由几个模块级绑定持有:payload、json、restored。

核心语句

const json = JSON.stringify(payload);

代码示例

// JSON.stringify 静默丢弃 undefined 字段、函数与 symbol
const payload = {
  id: 7,
  note: undefined,
  retry: () => {},
  token: Symbol('secret'),
  tags: ['a', undefined, 'b'],
};

const json = JSON.stringify(payload);
console.log('stringified:', json);

// 还原后:丢掉的字段消失,数组空洞变成 null
const restored = JSON.parse(json);
console.log('restored keys:', Object.keys(restored));
console.log('array hole became:', restored.tags[1]);

// 同一个 undefined:数组保留槽位写 null,对象键整个消失
console.log('array keeps slot as null:', JSON.stringify(['x', undefined]));
console.log('object drops the key:', JSON.stringify({ value: undefined }));