Hello World.🍺|

&漠。

园龄:3年8个月粉丝:0关注:0

js深拷贝

1.js深拷贝

function deepClone(obj, hash = new Map()) {

            if (!obj || typeof obj != "object") return obj;
            if (hash.get(obj)) return hash.get(obj);
            let cloneObj = Array.isArray(obj) ? [] : {};
            hash.set(obj, cloneObj);
            for (let i in obj) {
                if (obj.hasOwnProperty(i)) {
                    obj[i] = deepClone(obj[i], hash);
                }
            }
            return obj;
        }
        let a = [1, 2, 3, 4, { name: "栋dong", age: 20, speak: () => { console.log("我好牛逼") }, array: [0, 8, 1, 4] }];
        b = deepClone(a);
        console.log(b)


//**********处理更多

        function deepCopy(data, hash = new WeakMap()) {
        if(typeof data !== 'object' || data === null){
                throw new TypeError('传入参数不是对象')
            }
        // 判断传入的待拷贝对象的引用是否存在于hash中
        if(hash.has(data)) {
                return hash.get(data)
            }
        let newData = {};
        const dataKeys = Object.keys(data);
        dataKeys.forEach(value => {
            const currentDataValue = data[value];
            // 基本数据类型的值和函数直接赋值拷贝 
            if (typeof currentDataValue !== "object" || currentDataValue === null) {
                newData[value] = currentDataValue;
            } else if (Array.isArray(currentDataValue)) {
                // 实现数组的深拷贝
                newData[value] = [...currentDataValue];
            } else if (currentDataValue instanceof Set) {
                // 实现set数据的深拷贝
                newData[value] = new Set([...currentDataValue]);
            } else if (currentDataValue instanceof Map) {
                // 实现map数据的深拷贝
                newData[value] = new Map([...currentDataValue]);
            } else { 
                // 将这个待拷贝对象的引用存于hash中
                hash.set(data,data)
                // 普通对象则递归赋值
                newData[value] = deepCopy(currentDataValue, hash);
            } 
       }); 
      return newData;
  }

本文作者:yang10086

本文链接:https://www.cnblogs.com/yang10086/p/17025002.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   &漠。  阅读(9)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起