js深度克隆

48次阅读

共计 448 个字符,预计需要花费 2 分钟才能阅读完成。

//var arr = [1,2,[11,22]];
var arr = {
    name:"xiao",
    age:{
        first:"diyi",
        two:"第二"
    }
};
function deepCopy(parm){
    let res;
    if(Object.prototype.toString.call(parm) == "[object Array]"){   // 数组
        res = [];
        for(var i = 0;i < parm.length;i++){res[i] = deepCopy(parm[i]);
        }
    }else if(Object.prototype.toString.call(parm) == "[object Object]"){  // 对象
        res = {};
        for(var i in parm){res[i] = deepCopy(parm[i]);
        }
    }else{return parm;}
    return res;
}
var newarr = deepCopy(arr);
//arr[1] = "xx";
arr.name = "gejin";
console.log(newarr);

正文完
 0