淺拷貝只復制指向某個對象的指針,而不復制對象本身,新舊對象還是共享同一塊內存。
淺拷貝的實現方式
- Object.assign():需注意的是目標對象只有一層的時候,是深拷貝
- Array.prototype.concat()
- Array.prototype.slice()
深拷貝就是在拷貝數據的時候,將數據的所有引用結構都拷貝一份。簡單的說就是,在內存中存在兩個數據結構完全相同又相互獨立的數據,將引用型類型進行復制,而不是只復制其引用關系。
function checkedType (target) {
// return Object.prototype.toString.call(target).slice(8, -1)
return Object.prototype.toString.call(target).slice(8,-1)
}
function clone(target) {
//判斷拷貝的數據類型
//初始化變量result 成為最終克隆的數據
let result,
targetType = checkedType(target)
if (targetType === 'Object') {
result = {}
} else if (targetType === 'Array') {
result = []
} else {
return target
}
//遍歷目標數據
for (let i in target) {
//獲取遍歷數據結構的每一項值。
let value = target[i]
//判斷目標結構里的每一值是否存在對象/數組
if (checkedType(value) === 'Object' || checkedType(value) === 'Array') {
//對象/數組里嵌套了對象/數組
//繼續遍歷獲取到value值
result[i] = clone(value)
} else {
//獲取到value值是基本的數據類型或者是函數。
result[i] = value
}
}
return result
}
console.log(clone(111))