使用JSON
const x = JSON.parse(JSON.stringify(a))
缺点:
- 不支持Date、正则、undefined、函数等数据
- 不支持引用(环装结构)
递归
要点:
-
递归
-
判断类型
-
检查环
-
不拷贝原型上的属性
const deepClone = (a, cache) => {
if (!cache) {// 设置缓存避免环形引用报错
cache=new Map()//用map因为map的key可以是对象
}
if (a instanceof Object) {
if (cache.get(a)) { return cache.get(a) }
let result;
if (a instanceof Function) {
if (a.prototype) {
result=function(){return a.apply(this,arguments)
}
} else {//箭头函数
result=(...args)=>{return a.call(undefined,...args)}
}
}
else if (a instanceof Array) {
result=[]
}
else if (a instanceof Date) {
result=new Date(a-0)
}
else if (a instanceof RegExp) {
result=new RegExp(a)
}
else {
result={}
}
cache.set(a, result)
for (let key in a) {
if (a.hasOwnProperty(key)) {//不拷贝从原型继承来的属性
result[key]=deepClone(a[key],cache)
}
}
return result
} else {
return a
}
}