js深コピー

7670 ワード

        //            
        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);;