方法一:Object.assign
function copy(obj){
return Object.assign({}, obj);
}
方法二:…展开运算符
function copy(obj){
return { …obj };
}
方法一,方法二是浅拷贝,也就是当对象层级大于2层时,复制到的还是地址信息
let a = {age:1,
jobs: {first:'FE’}
}
let b = copy(a)
a.jobs.first =‘native'
console.log(b.jobs.first)// native
方法三:JSON
function copy(obj){
return JSON.parse(JSON.stringify( obj ));
}
- 会忽略undefined,fn
- 不能序列化函数
- 不能解决循环引用的对象
方法四:MessageChannel
function structuralClone(){
return new Promise(resolve =>{
const {port1,port2} = new MessageChannel()
port2.onmessage = ev => resolve(ev.data)
port1.postMessage(obj)
})
}
obj2 = await structuralClone(obj1);
- 如果对象中有函数,会报错
- 可以解决循环引用的对象
- 异步