实现说明
各个操作都建立在顶层绑定之上: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 }));