实现说明
node、safe 定义在模块顶层,中间不经过函数作用域。
模块级对象字面量,键名固定:id、next。
使用要点
- 每一步打印都带着自己的标签:
error:、safe:。
常见问题
需要安装第三方包吗?
不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 状态都挂在模块顶层:node、safe。
核心语句
const safe = JSON.stringify(node, (key, value) => (key === 'next' ? '[linked]' : value));
JSON.stringify(node);
代码示例
const node = { id: 1, next: null };
node.next = node; // linked-list style circular reference
// JSON.stringify throws a TypeError as soon as it hits a circular reference
try {
JSON.stringify(node);
} catch (err) {
console.log('error:', err instanceof TypeError);
}
// the logging path uses a replacer to skip the cycle-forming key instead of letting the whole serialization crash
const safe = JSON.stringify(node, (key, value) => (key === 'next' ? '[linked]' : value));
console.log('safe:', safe);