let obj = {
name:'zhagnsan',
age:30,
school:'pinghai'
}
object.assign
function copy(obj){
return Object.assign({},obj)
}
console.log(copy(obj))
...展开运算符
function copy2(obj){
return {...obj}
}
console.log(copy2(obj))
let a = {
age:1,
jobs:{first:'FE'}
}
let b = copy(a)
a.jobs.first = 'native'
console.log(b.jobs.first)
console.log(a.jobs.first)
//浅拷贝,当对象层级大于2级时候,原来的对象属性也被改变了
深拷贝
function copyDeep(obj){
return JSON.parse(JSON.stringify(obj))
}
console.log(copyDeep(obj))
messageChannel
function structuralClone(){
return new Promise(resolve =>{
const{port1,port2} = new MessageChannel()
port2.onmessage = ev => resolve(ev.data)
port1.postMessage(obj)
})
}
obj2 = structuralClone(obj)
console.log(obj2)
网友评论