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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值