javascript 赋值 浅拷贝 深拷贝

    let originObj = {
        name: 'Lili',
        age: 12,
        families: ['Jhon', 'Linda', 'Mike']
    }
    // 赋值 (赋值获得的是指向原对象的一个地址指针,它和原对象操作的是同一个数据源,任何操作都会互相影响)
    let copyObj = originObj
    copyObj.age = 24
    console.log('赋值改变之后的原始值',originObj) 

    // 浅拷贝 (浅拷贝,拷贝的是某个对象,却不拷贝某个对象的子对象,因此,操作基本类型的数据,不会影响数据源,但是操作引用类型的数据,同时也会改变数据源)
    // 浅拷贝的几种实现  Object.assign()  Array.prototype.concat()  Array.prototype.slice()
    function shallowCopy(obj) {
        let result = {} ;
        for(var prop in obj) {
            if(obj.hasOwnProperty(prop)) {
                result[prop] = obj[prop]
            }
        }
        return result;
    }

    let shaollowCopyObj = shallowCopy(originObj)
    shaollowCopyObj.age = '12'
    shaollowCopyObj.families[0] = 'shallowCopyObj'
    console.log('浅拷贝改变之后的原始值',originObj)

    // 深拷贝
    // JSON.parse(JSON.stringify()) 将一个对象通过JSON.stringify 转换为字符串再通过 JSON.parse 转换为对象实现的是深拷贝
    // 但是这里不能处理函数,因为 JSON.stringify 方法是将js的一个值(对象或者是数组) 转换为js字符串
    // 1.定义检测数据类型的功能函数
    function checkedType (target) {
        return Object.prototype.toString.call(target).slice(8, -1)
    }
    // console.log(checkedType(originObj))  //[object object]
    function deepCopy (target) {
        let result
        let 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') {
                result[i] = deepCopy(value)
            } else {
                result[i] = value
            }
        }

        return result;
    }
    let deepCopyObj = deepCopy(originObj)
    deepCopyObj.age = 44;
    deepCopyObj.families[2] = 'deppCopyObj'
    console.log('深拷贝改变之后的原始值', originObj)

猜你喜欢

转载自blog.csdn.net/chengQunBin/article/details/85259221