深拷贝的方法
1.JSON.parse(JSON.stringify()) (不能拷贝function)
let list = [
{ id: 1, name: '李知恩', city: '首尔' },
{ id: 2, name: '李荣浩', city: '蚌埠' },
{ id: 1, name: '杨超越', city: '上海' },
]
let newList = JSON.parse(JSON.stringify(list))
newList.push({ id: 888 })
console.log(list, newList);
2.递归拷贝
//引用数据类型,要么是数组,要么是对象
function deepClone (source) {
// 判断传入的是数组还是对象
const targetObj = source.constructor === Array ? [] : {}
for (let key in source) {
//判断是否有当前属性
if (source.hasOwnProperty(key)) {
//引用数据类型
if (source[key] && typeof source[key] === 'object') {
//递归
targetObj[key] = deepClone(source[key])
} else {
//基本数据类型
targetObj[key] = source[key]
}
}
}
return targetObj
}
let obj = {
name: '张三',
age: 24,
obj1: { name: '李四', age: 30 },
arr: [1, 2, 3, 4]
}
let newObject = deepClone(obj)
newObject.name = '李知恩'
newObject.arr.push('全世界最好的李知恩')
console.log(obj, newObject)