第一种:使用JSON格式转换,无法对循环对象进行克隆
function deepClone(obj){
return JSON.parse(JSON.stringify(obj))
}
缺点:无法对循环对象进行克隆,例如以下对象
const a={a:1,b:2};
a.c=a;
const b=deepClone(a);
//throw 抛出异常
第二种:使用类型判断迭代转换 ,可对任意对象克隆
function deepClone(obj) {
const objectMap = new Map();
const _deepClone = (value) => {
const type = typeof value;
if (type !== 'object' || type === null) {
return value;
}
if (objectMap.has(value)) {
return objectMap.get(value);
}
const result = Array.isArray(value) ? [] : {};
objectMap.set(value, result);
for (const key in value) {
result[key] = _deepClone(value[key]);
}
return result;
}
return _deepClone(obj);
}
第三种 :通过序列化和反序列化进行克隆,当消息包含函数、Symbol等不可序列化的值时,就会报无法克隆的DOM异常。
function deepClone(obj) {
return new Promise(res => {
const { port1, port2 } = new MessageChannel();
port1.postMessage(obj);
port2.onmessage = msg => {
res(msg.data);
}
})
}