- 2 种浅拷贝
- 3 种深拷贝(包括手写实现)
2 种浅拷贝
//1
let b = Object.assign({}, a)
//2
let b = {...a}
3 种深拷贝(包括手写实现)
1. JSON.parse方法
let b = JSON.parse(JSON.stringify(a))
缺点:
1. 会忽略undefined、Symbol
2. 不能序列化函数
3. 不能解决循环引用的对象
2. 调用lodash
var _ = require('lodash')
let b = _.cloneDeep(a)
3. 手写实现
function deepClone(a){
if(typeof a!=='object'||a==null){
return a
}
let b
if(a instanceof Array){
b=[]
}else{
b={}
}
for(let key in a){
if(a.hasOwnProperty(key)){
b[key]=deepClone(a[key])
}
}
return b
}
const a={
name:'art',
action:'click',
next:'button',
age:18,
person:{
age:19,
content:{
address:'somewhere',
others:0
}
},
fn() {
console.log(this.action)
}
}
const b= deepClone(a)
console.log(b, b.fn)
console.log(b===a)