特殊的assign()
如果assign()的拷贝类型是简单类型,拷贝形式为深拷贝
let obj_1 = {
name: 'Faker',
age: 24
}
let obj_2 = {
}
Object.assign(obj_2, obj_1)
console.log(obj_2) // {name: "Faker", age: 24}
如果assign()的拷贝形式为对象或其它引用类型,拷贝类型为浅拷贝
let obj_1 = {
name: 'Faker',
age: 24,
food: {
vegetable: 'broccoli',
mainFood: 'poke',
}
}
let obj_2 = {
name: 'Bang',
age: 23,
food: {
vegetable: '1',
mainFood: '1',
coffee: 'Americano' // 多了一个coffee属性
}
}
Object.assign(obj_2, obj_1)
console.log(obj_2) // coffee属性丢失
// {name: "Faker", age: 24, food: {vegetable: "broccoli", mainFood: "poke"}}
使用JSON实现类的深拷贝
let obj_1 = {
name: 'Faker',
age: 24,
food: {
vegetable: 'broccoli',
mainFood: 'poke',
}
}
let str = JSON.stringify(obj_1)
let obj_2 = JSON.parse(str)
console.log(obj_2)
// {name: "Faker", age: 24, food: {vegetable: "broccoli", mainFood: "poke"}}
手写深拷贝
let checkType = data => {
return Object.prototype.toString.call(data).slice(8, -1)
}
let deepClone = target => {
let targetType = checkType(target)
let result
if (targetType === 'Object') {
result = {}
}
else if (targetType === 'Array') {
result = []
}
else {
return target
}
for (let i in target) {
let value = target[i]
if (checkType(value) === 'Object' || checkType(value) === 'Array') {
result[i] = deepClone(value)
} else {
result[i] = value
}
}
return result
}