实现说明
演示用的数据放在这几个模块级绑定中:original、copy、viaJson。
使用要点
- 每一步打印都带着自己的标签:
original deep:、copy deep:、original tags size:。
常见问题
需要安装第三方包吗?
不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 跨调用保留的状态放在这些顶层绑定里:original、copy、viaJson。
核心语句
const viaJson = JSON.parse(JSON.stringify(original));
const copy = structuredClone(original);
代码示例
const original = {
id: 7,
createdAt: new Date('2026-11-17T10:00:00Z'),
tags: new Set(['alpha', 'beta']),
meta: new Map([['region', 'eu']]),
nested: { deep: { value: 1 } },
};
// structuredClone:保留 Date/Map/Set,支持循环引用
const copy = structuredClone(original);
copy.nested.deep.value = 99;
copy.tags.add('gamma');
console.log('original deep:', original.nested.deep.value);
console.log('copy deep:', copy.nested.deep.value);
console.log('original tags size:', original.tags.size);
console.log('copy is Date:', copy.createdAt instanceof Date);
console.log('copy map region:', copy.meta.get('region'));
// JSON 往返的对照:Date 退化成字符串、Map/Set 直接丢失
const viaJson = JSON.parse(JSON.stringify(original));
console.log('json copy createdAt type:', typeof viaJson.createdAt);
console.log('json copy tags:', viaJson.tags);