手写JS深拷贝

1.使用JSON.stringify,JSON.parse

该方法只能拷贝Object对象,而无法拷贝undefined,function,RegExp等。

function deepCopy1(obj) {
    // 使用JSON.stringify,JSON.parse
    let objString = JSON.stringify(obj);
    return JSON.parse(objString);
}

const obj1 = {
    name: 'tototoo',
    age: 23,
    hobbies: [1, 2, 3]
};

const obj2 = deepCopy1(obj1);
obj2.age = 22;
obj2.hobbies[0] = 0;
// obj1 { name: 'tototoo', age: 23, hobbies: [ 1, 2, 3 ] }
console.log("obj1", obj1);
// obj2 { name: 'tototoo', age: 22, hobbies: [ 0, 2, 3 ] }
console.log("obj2", obj2);

2.使用Object.assign(target, source)

该方法不能拷贝对象内部的对象,无法完成深拷贝。

function deepCopy2(obj) {
    return Object.assign({}, obj);
}

const obj1 = {
    name: 'tototoo',
    age: 23,
    hobbies: [1, 2, 3],
    address: undefined,
    pointer: null
};

const obj2 = deepCopy2(obj1);
obj2.age = 22;
obj2.hobbies[0] = 0;
obj2.address = 'beijing';
/* 
obj1 { name: 'tototoo',
  age: 23,
  hobbies: [ 0, 2, 3 ],
  address: undefined,
  pointer: null }
*/
console.log("obj1", obj1);
/*  obj2 { name: 'tototoo',
  age: 22,
  hobbies: [ 0, 2, 3 ],
  address: 'beijing',
  pointer: null }
*/
console.log("obj2", obj2);

3.使用递归的方式拷贝

function deepCopy3(obj) {
    let result = null;
    // 1.判断是对象类型还是普通数据类型,普通数据类型直接赋值
    if (typeof obj === 'object') {
        // 2.若是对象类型,进行细分:[],{},RegExp,null
        // 2.1若是数组
        if (Array.isArray(obj)) {
            result = [];
            for (let i = 0; i < obj.length; i++) {
                // 递归判断一下若有对象,在进行深拷贝
                result.push(deepCopy3(obj[i]));
            }
        } else if (obj.constructor === RegExp) {
            result = obj;
        } else if (obj === null) {
        	result = obj;
        } else { //普通对象
            result = {};
            // 保留原来对象类型,即原型上的信息
            if (obj.__proto__) {
				result.__proto__ = obj.__proto__;
			}
            for (key in obj) {
                result[key] = deepCopy3(obj[key]);
            }
        }
         
        // RegExp,null可以直接赋值,[],{}需要递归
    } else { // 普通数据类型或者函数
        result = obj;
    }
    return result;
}

let obj = {
    name: 'tt',
    family: {
        father: 'ff'
    },
    info: [1, 2, 3, 4],
    age: 16,
    fuc: function() {}
};

let obj_ = deepCopy3(obj);
obj_.family['father'] = 'Trump';
obj_.info.push(0);
/*
obj { name: 'tt',
  family: { father: 'ff' },
  info: [ 1, 2, 3, 4 ],
  age: 16,
  fuc: [Function: fuc] }
*/
console.log("obj", obj);
/*
obj_ { name: 'tt',
  family: { father: 'Trump' },
  info: [ 1, 2, 3, 4, 0 ],
  age: 16,
  fuc: [Function: fuc] }
*/
console.log("obj_", obj_);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值