js深拷贝

        //判断类型 是数组还是对象
        function getType(data) {
            return Object.prototype.toString.call(data).slice(8, -1);
        }

        function deepCopy(data) {
            //1.根据数据类型,创建对应空数组或者空对象
            if (getType(data) === "Array") {
                var res = [];
            } else if (getType(data) === "Object") {
                var res = {};
            } else {
                return data;
            }
            //2.循环赋值
            for (var key in data) {
                console.log(getType(data[key]));
                // 在循环过程中,如果遇到一个对象,
                // 针对于这个对象再进行深拷贝
                if (getType(data[key]) === ("Array" || "Object")) {
                    res[key] = deepCopy(data[key]); //递归
                } else {
                    res[key] = data[key];
                }

            }
            //3.返回复制好的对象
            return res;
        }
        /* 
         [1, 2, 3, ["a", "b", "c"]]
         var res = []
         res
         0 : 1
         1 : 2
         2 :3
         3 : deepCopy(data)  [a,b,c]   
              var res = []
                 0 : a
                 1 : b
                 2 : c
        */
        var arr = [1, 2, 3, ["a", "s", "d"]];
        var obj = {
            "class": "active",
            "student": {
                "student1": "张三",
                "student2": "李四"
            }
        }
        var arr1 = deepCopy(arr);;

你可能感兴趣的:(javascript)