【根據(jù)深拷貝的代碼實(shí)現(xiàn)過程給自己講解一遍栏豺,就懂了】
/**
?* 深拷貝
?*/
const obj1 = {
? ? age: 20,
? ? name: 'xxx',
? ? address: {
? ? ? ? city: 'beijing'
? ? },
? ? arr: ['a', 'b', 'c']
}
// const obj2 = obj1
const obj2 = deepClone(obj1)
obj2.address.city = 'shanghai'
obj2.arr[0] = 'a1'
console.log(obj1.address.city) // -> beijing
console.log(obj1.arr[0]) // -> a
? ? // 1.obj2改了贬派,obj1也被改了。
? ? // 2.深拷貝就是obj2改值所计,obj1不變
/**
?*深拷貝
?*
?* @param {Object} [obj={}] obj要拷貝的對(duì)象
?* @return {*}
?*/
function deepClone(obj = {}) {
? ? if (typeof obj !== 'object' || obj == null) {
? ? ? ? // obj 是 null,或者不是對(duì)象和數(shù)組,直接返回
? ? ? ? return obj
? ? }
? ? // 初始化返回結(jié)果
? ? let result
? ? if (obj instanceof Array) {
? ? ? ? result = []
? ? } else {
? ? ? ? result = {}
? ? }
? ? for (let key in obj) {
? ? ? ? // 保證 key 不是原型的屬性
? ? ? ? if (obj.hasOwnProperty(key)) { // 保證key是obj的屬性困鸥。
? ? ? ? ? ? //遞歸調(diào)用;8枨住!
? ? ? ? ? ? result[key] = deepClone(obj[key])
? ? ? ? }
? ? } // 層次很深的東西就需要這樣一遍一遍遞歸澜驮,把值類型給拷貝出來(lái)应结,這樣才能完成深拷貝
? ? // 返回結(jié)果
? ? return result
}