深拷貝與淺拷貝

  1. 淺拷貝:只拷貝一層基本類型數(shù)據(jù),遇見引用類型還是復制的地址,所以拷貝后的數(shù)據(jù) 和 拷貝前的數(shù)據(jù),還存在共用同一個地址的屬性,此時拷貝并不徹底,兩份數(shù)據(jù)還會相互影響,所以叫淺拷貝
  2. 深拷貝:完整的把數(shù)據(jù)的任意層級屬性和值拷貝到新數(shù)據(jù)上,拷貝前后的兩個數(shù)據(jù)完全一樣,但是是不同的地址,相互不會影響。
let obj = { a: 1, b: 2, c: 3, d: { dd: 44 } }

// 兩個變量指向同一個地址空間 不是拷貝
let obj1 = obj

// Object.assign是語言提供的淺拷貝方法,把第二個參數(shù)開始的數(shù)據(jù)的屬性都拷貝到第一個參數(shù)上
// let obj2 = Object.assign({}, obj, obj1, obj2)

// 淺拷貝: 拷貝原數(shù)據(jù) 到新的數(shù)據(jù)上,但是只是復制一層數(shù)據(jù),對于數(shù)據(jù)項如果是引用類型,那么還是復制的地址,
// 所以拷貝后的數(shù)據(jù) 和 拷貝前的數(shù)據(jù),還存在共用同一個地址的屬性
// let obj3 = {}
// for (let key in obj) {
//  console.log('key-value: ', key, obj[key])
//  obj3[key] = obj[key]
// }

// 深拷貝

// source 待拷貝的源數(shù)據(jù)
// 不完善的版本 不支持數(shù)組
function cloneDeep(source) {
    const ret = {}

    for (let key in source) {
        console.log('key-value: ', key, source[key])
        if (typeof source[key] == 'object') {
            ret[key] = cloneDeep(source[key])
        } else {
            ret[key] = source[key]
        }
    }

    console.log('ret: ', ret)
    return ret
}

// const obj4 = cloneDeep(obj)

let arr1 = [1, 2, 3, 4, [55, 66, 77], { a: 1 }]
function cloneDeep1(source) {
    // 獲取被拷貝的數(shù)據(jù)的類型
    let type = Object.prototype.toString.call(source).slice(8, -1)

    let ret = {}

    // 如果被拷貝的數(shù)據(jù)是一個數(shù)組,ret賦值為空數(shù)組
    if (type === 'Array') {
        ret = []
    }

    if (type === 'Object') {
        for (let key in source) {
            // console.log('key-value: ', key, source[key])
            if (typeof source[key] == 'object') {
                ret[key] = cloneDeep1(source[key])
            } else {
                ret[key] = source[key]
            }
        }
    } else if (type === 'Array') {
        for (let i = 0; i < source.length; i++) {
            if (typeof source[i] === 'object') {
                ret[i] = cloneDeep1(source[i])
            } else {
                ret[i] = source[i]
            }
        }
    }

    // console.log('ret: ', ret)
    return ret
}

const arr2 = cloneDeep1(arr1)
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容