//浅拷贝
var obj = {
name: 'jack',
age: 18
}
const newObj = obj
console.log('obj', obj)
console.log('newObj', newObj)
//深拷贝
var oldObj = {
name: 'jack',
age: 18
}
function deepClone(obj) {
let result
if (typeOf obj !== 'object') {
return obj
}
if (obj instanceof Array) {
result = []
} else {
result = {}
}
for (let i in obj) {
result[i] = deepClone(obj[i])
}
return result
}
const newObj = deepClone(oldObj)
newObj.name = 'tom'
console.log('oldObj', oldObj)
console.log('newObj', newObj)
//利用 JSON.parse() 和 JSON.stringify()实现深拷贝
var obj = {
name: '小明',
grilFriend: { name: '小红' }
}
function deepClone(obj) {
let _obj = JSON.stringify(obj);
let data = JSON.parse(_obj);
return data
}
var newObj = deepClone(obj);
newObj.grilFriend.name = '小花'
console.log(obj, newObj)