JS实现对象深拷贝

方式一:通过JSON的stringify与parse方法实现

let obj = {a: 1, b: [{c: 2, d: 3}, {e: 4, f: 5}], g: 6}
let result = JSON.parse(JSON.stringify(obj));
    
console.log(result, obj, result === obj);             
console.log(result.b, obj.b, result.b === obj.b);    
console.log(result.b[0], obj.b[0], result.b[0] === obj.b[0]);

执行结果:

方式二:通过递归的方法实现

 const deepCopy = (obj) => {
    let target  = null
    if(typeof obj === 'object'){
        if(Array.isArray(obj)){ //数组
            target = [];
            obj.forEach(item => {
                target.push(deepCopy(item));
            })
        }else if(obj){
            target = {}
            let objKeys = Object.keys(obj);
            objKeys.forEach(key => {
                target[key] = deepCopy(obj[key]);
            })
        }else{
            target = obj
        }
    }else{
        target = obj;
    }
    return target
}
 
 
let obj = {a: 1, b: [{c: 2, d: 3}, {e: 4, f: 5}], g: 6}
let result = deepCopy(obj);
console.log(result, obj, result === obj)             
console.log(result.b, obj.b, result.b === obj.b)     
console.log(result.b[0], obj.b[0], result.b[0] === obj.b[0])

执行结果:

方式三:使用循环的方式实现

const deepCopy = (obj) => {
    //浅拷贝子节点
    let handleChild = (child) => {
        if(typeof child === 'object'){
            if(Array.isArray(child)){ // 数组
            return [...child]
            }else if(child){ // 对象
            return {...child}
            }else{ // null
            return child
            }
        }else{ // 值类型
            return child
        }
    }
    let arr = [];
    let target = {result: obj};
    let current = target; 
    while(current){
    if(typeof current === 'object'){
        if(Array.isArray(current)){ //数组
        current.forEach((item, index) => {
            let child = handleChild(item)
            current[index] = child;
            arr.push(child);
        })
        }else if(current){ //对象
        let objKeys = Object.keys(current);
        objKeys.forEach(key => {
            let child = handleChild(current[key]);
            current[key] = child;
            arr.push(child);
        })
        }else{ //null
        temp = current;
        }
    }
    current = arr.shift()
    }
    return target.result
}
 
let obj = {a: 1, b: [{c: 2, d: 3}, {e: 4, f: 5}], g: 6}
let result = deepCopy(obj);
console.log(result, obj, result === obj)             
console.log(result.b, obj.b, result.b === obj.b)     
console.log(result.b[0], obj.b[0], result.b[0] === obj.b[0])

执行结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值