深拷贝浅拷贝

  •     2    种浅拷贝
  •     3    种深拷贝(包括手写实现)

    2    种浅拷贝

//1 
let b = Object.assign({}, a)

//2
let b = {...a}

    3    种深拷贝(包括手写实现)

1. JSON.parse方法

let b = JSON.parse(JSON.stringify(a))

缺点:

        1. 会忽略undefined、Symbol

        2. 不能序列化函数

        3. 不能解决循环引用的对象

2. 调用lodash

var _ = require('lodash')
let b = _.cloneDeep(a)

3. 手写实现

function deepClone(a){
    if(typeof a!=='object'||a==null){
        return a
    }
    let b
    if(a instanceof Array){
        b=[]
    }else{
        b={}
    }
    for(let key in a){
        if(a.hasOwnProperty(key)){
            b[key]=deepClone(a[key])
        }
    }
    return b
}

const a={
    name:'art',
    action:'click',
    next:'button',
    age:18,
    person:{
        age:19,
        content:{
            address:'somewhere',
            others:0
        }
    },
    fn() {
        console.log(this.action)
    }
}
const b= deepClone(a)
console.log(b, b.fn)
console.log(b===a)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值