js实现深克隆,深拷贝

215 阅读1分钟

一、一维数组,对象深克隆

1.JSON.parse(JSON.stringfy()) ;

代码如下:

let obj1 = { a: 1, b: 2 };
let obj2 = JSON.parse(JSON.stringfy(obj1));
obj2.a = 1000;
console.log(obj1);
//输出  Object { a: 1, b: 2 }
console.log(obj2)
//输出 Object { a: 1000, b: 2 }

2.展开运算符: ... ;

代码如下:

let obj1 = { a: 1, b: 2 };
let obj2 = {...obj1}
obj2.a = 1000;
console.log(obj1);
//输出  Object { a: 1, b: 2 }
console.log(obj2)
//输出 Object { a: 1000, b: 2 }

二、多维数组,对象深克隆

代码如下

       function deepClone( value ) {
            //判断是否为null或者undefined; null == undefined//true
            if (value == null) return value;

            //判断是否为正则
            if (value instanceof RegExp) return new RegExp(value);

            //判断是否Date
            if (value instanceof Date) return new Date(value);

            //判断是否为基本数据类型,Function
            if (typeof value != "object") return value;

            //通过new 构造器 创建新的 obj 或者 ary
            let newBox = new value.constructor();

            for (let key in value) {
                //for in 循环会遍历私有属性和 __proto__;
                if (value.hasOwnProperty ( key )) {
                    //递归实现深度克隆
                    newBox [key] = deepClone( value[ key ] )
                }
            }

            return newBox

        }
        
        
        let obj1 = { a: 1, b: { age: 100 } };
        let obj2 = deepClone( obj1 );
        obj2.b.age = 2000
        console.log( obj1 )   //{ a: 1, b: { age: 100 } }
        console.log( obj2 )   //{ a: 1, b: { age: 2000 } }
        let arr1 = [ 1, [ 2, 3, 4 ] ]
        let arr2 = deepClone( arr1 )
        arr2[1]=[ 11111, 11111 ]
        console.log( arr1 )   // [ 1, [ 2, 3, 4 ] ]
        console.log( arr2 )   //  [ 1, [ 1111, 11111] ]