1、浅拷贝
Object.assign()
let a = {name:'le'}
let b = {age:8}
let d = {}
Object.assign(d,a,b)
console.log(d)
//或者
let d = Object.assign(a,b)
console.log(d)
复制代码
es6扩展符
let a = {name:'le'}
let b = {age:8}
let c = {...a,...b}
复制代码
2.深拷贝具有递归特性 JSON.parse(JSON.stringify())
let a = {name:'le',fn:function(){
console.log('fn')
}}
let e = JSON.parse(JSON.stringify(a))
console.log(e)
//{ name: 'le', age: 8 }
复制代码
如果对象里没有函数是可以达到目的的,但是对象里有函数则会将其忽略
3.深拷贝 递归拷贝 解决函数属性问题
function deepClone(obj){
if(obj === null) return null;
if(typeof obj !== 'object') return obj;
if(obj instanceof RegExp) return new RegExp(obj);
if(obj instanceof Date) return new Date(obj);
let newObj = new obj.constructor();
for(let key in obj){
newObj[key] = deepClone(obj[key]);
}
return newObj;
};
let o = {name:{name:1}}
let test = deepClone(o);
o.name.name = 'hello';
console.log(test);
复制代码