方法一: 用JSON
const b = JSON.parse(JSON.stringify(a))
缺点:
-
不支持 Date、正则、undefined、函数等数据
-
不支持引用
方法二:用递归
要点:
-
递归
-
判断类型
-
检查环
-
不拷贝原型上的属性
//保存已经克隆过的映射关系
const cache = new Map()
const deepClone = (a)=>{
if (cache.get(a)) {
return cache.get(a)
}
if (a instanceof Object) {
let result = undefined
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) {
//a-0得到时间戳
result = new Date(a-0)
}else if (a instanceof RegExp) {
result = new RegExp(a.source,a.flags)
}else{
result = {}
}
cache.set(a,result)
for(let key in a){
//不拷贝原型
if(a.hasOwnProperty(key)){
result[key] = deepClone(a[key])
}
}
return result
}else{
return a
}
}