js对象或数组深拷贝

对于一个对象深拷贝,可以使用JSON来做:

 

let obj_init = {
    person: {
        name: "tf",
        age: 22
    },
    arr: [
        {
            id: 1,
            name: "play",
            arr: [1, 2]
        },
        ["t", "f"]
    ],
    index: "1",
    other: null
};

// type 1
let obj_copy1 = JSON.parse(JSON.stringify(obj_init));

console.log(obj_init.person === obj_copy1.person);  // false
console.log(obj_init.arr[0] === obj_copy1.arr[0]);  // false

用递归的方法也可以实现

let deep_copy = function f(obj) {
    let new_value;
    if(typeof obj === 'object' && obj != null){
        if(obj instanceof Array){
            new_value = [];
            for(let i=0;i<obj.length;i++){
                if(typeof obj[i] !== 'object' || obj[i] === null){
                    new_value[i] = obj[i];
                }else{
                    new_value.push(f(obj[i]));
                }
            }
        }else{
            new_value = {};
            for(let item in obj){
                if(obj.hasOwnProperty(item)){
                    if(typeof obj[item] !== 'object' || obj[item] === null){
                        new_value[item] = obj[item];
                    }else{
                        Object.assign(new_value, { [item]: f(obj[item])});
                    }
                }
            }
        }
    }else{
        new_value = obj;
    }

    return new_value;
};

let obj_copy2 = deep_copy(obj_init);
console.log(obj_copy2.person === obj_init.person);  // false
console.log(obj_copy2.arr[0] === obj_init.arr[0]);  // false

因为在严格模式下,不可以使用arguments.callee,所以这里采用了一个变量函数的方法并且等式右边不是匿名函数。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值