深拷贝与浅拷贝

// 深拷贝与浅拷贝

// let target = {
// a: {
// b: {
// c: 1,
// f: 2
// },
// e: 3,
// g: 11
// }
// }
// let source = {
// a: {
// b: {
// c: 1,
// f: 2
// },
// e:5
// }
// }
// //结果 g数据缺失
// Object.assign(target, source) //所以 Object.assign 在拷贝对象上是有问题的 复杂对象会缺失 浅拷贝
// console.log(target)

// let a = 5 // 两个值互相不影响 深拷贝
// let b = a
// a = 6
// console.log(a, b)

// let obj1 = {
// name: 'hky',
// age: 27
// }

// let obj2 = obj1

// obj1.age = 18
// console.log(obj1)
// console.log(obj2)

// let obj1 = {
// name: 'hky',
// age: 27
// }


// JSON是字符串 键值对型的
// '{"a": "hello", "b": "world"}'
// let obj = JSON.parse('{"a": "hello", "b": "world"}')
// console.log(obj)

// let str1 = JSON.stringify(obj)
// console.log(str1)

// let str1 = JSON.stringify(obj1)
// let obj2 = JSON.parse(str1)
// obj1.age = 18
// console.log(obj2)

// 基本数据类型就是深拷贝的
//type of 判断基本数据类型
// 检查类型的函数
let checkType = data => {
return Object.prototype.toString.call(data).slice(8, -1) //toString 判断数据的类型
}


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]
let valueType = checkType(value)
if (valueType === 'Object' || valueType === 'Array') {
result[i] = deepClone(value) //递归
} else {
result[i] = value
}
}
return result
}

// let arr1 = [1, 2, {age: 18}]
// let arr2 = deepClone(arr1)
// arr1[1].age = 19
// console.log(arr2)

let obj1 = {
name: 'hky',
hobby: ['coding', 'eating']
}

let obj2 = deepClone(obj1)

obj2.hobby[0] = 'sleeping'

console.log(obj1, obj2)

posted @ 2021-02-23 21:32  贺可英  阅读(35)  评论(0)    收藏  举报