克隆obj
Object.assign():对象合并,实现对象的浅克隆
画图理解
对象展开运算符
{...obj},展开运算符,也只能展开第一级,也是浅克隆。
let newObj = {
...obj
}
深克隆 json.parse(json.stringify())
封装一个深克隆函数
代码啊
let obj = {
a:11,
b:[1,2,3],
c:{x:11},
s:function(){},
d:/^d+$/,
e:new Date()
}
function clonedeep(obj){
const constructor = obj.constructor;
if (obj === null) return null;
if(typeof obj !== "object") return obj;
if(/^(RegExp|Date)$/i.test(constructor.name)) return new constructor(obj)
let clone = new constructor()
for(let key in obj){
if(!obj.hasOwnProperty(key)) break;
clone[key] = clonedeep(obj[key])
}
return clone
}
let newobj = clonedeep(obj)
console.log(obj,newobj)
console.log(newobj === obj) //false
console.log(newobj.b === obj.b) //false
console.log(newobj.c === obj.c) //false
console.log(newobj.d === obj.d) //false
console.log(newobj.s === obj.s)