使用 structuredclone() 可以保留 date、map、set 等内置对象类型,而 json.parse(json.stringify()) 会将它们转为普通对象或字符串。对于不支持该 api 的环境,可编写基于 instanceof 的递归函数来手动处理类型还原。

为什么 JSON 序列化会丢失类型信息
因为 JSON.stringify() 在序列化时只识别基本数据类型和纯对象结构,遇到 Date 实例会调用其 toString() 方法转为字符串,遇到 RegExp 会转为空对象,导致反序列化后无法恢复原始类型。

const input = {
date: new Date('2023-01-01'),
regex: /test/g,
map: new Map([['key', 'value']])
};
const jsonStr = JSON.stringify(input);
console.log(jsonStr);
// {"date":"2023-01-01T00:00:00.000Z","regex":{},"map":{}}
const restored = JSON.parse(jsonStr);
console.log(restored.date instanceof Date); // false
console.log(restored.regex instanceof RegExp); // false
console.log(restored.map instanceof Map); // false如何使用 structuredClone 保持类型
structuredClone() 是浏览器和 Node.js 17+ 提供的原生深拷贝方法,它遵循结构化克隆算法,能正确识别并复制 Date、ArrayBuffer、Map、Set 等复杂类型。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
立即学习“Java免费学习笔记(深入)”;

const input = {
date: new Date('2023-01-01'),
regex: /test/g,
map: new Map([['key', 'value']]),
nested: {
set: new Set([1, 2, 3])
}
};
const cloned = structuredClone(input);
console.log(cloned.date instanceof Date); // true
console.log(cloned.regex instanceof RegExp); // true
console.log(cloned.map instanceof Map); // true
console.log(cloned.nested.set instanceof Set); // true
cloned.date.setFullYear(2024);
console.log(input.date.getFullYear()); // 2023 (未受影响)针对特定输入条件的类型还原逻辑
当需要兼容旧版环境且必须处理 RegExp 或 Function(需特殊处理)时,可以通过检查原型链来区分类型。以下代码展示了如何根据输入对象的构造函数进行针对性克隆,确保 RegExp 的标志位不被丢失。
function deepCloneWithTypes(obj, visited = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if (visited.has(obj)) return visited.get(obj);
let clone;
if (obj instanceof Date) {
clone = new Date(obj.getTime());
} else if (obj instanceof RegExp) {
clone = new RegExp(obj.source, obj.flags);
} else if (obj instanceof Map) {
clone = new Map();
obj.forEach((val, key) => clone.set(key, deepCloneWithTypes(val, visited)));
} else if (obj instanceof Set) {
clone = new Set();
obj.forEach(val => clone.add(deepCloneWithTypes(val, visited)));
} else if (Array.isArray(obj)) {
clone = [];
obj.forEach((val, index) => clone[index] = deepCloneWithTypes(val, visited));
} else {
clone = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
clone[key] = deepCloneWithTypes(obj[key], visited);
}
}
}
visited.set(obj, clone);
return clone;
}
const testObj = {
pattern: /abc/i,
data: new Set(['a', 'b'])
};
const result = deepCloneWithTypes(testObj);
console.log(result.pattern.test('ABC')); // true
console.log(result.data.has('a')); // true

















