//浅拷贝
var source={ id:1, name:'张三', cert:{ certNo:'211111111', certAddress:'北京市昌平区' } } var target={} var keys=Object.keys(source); keys.forEach(function(k,index,arr){ target[k]=source[k]; }) console.log(target)
// 深拷贝
var obj={ name:'22', age:12, card:['khjh','gg'], wife:{ name:'kkk' } } var obj1={}; //1 判断是不原始值 typeof()返回的是不是object //2 判断是数组还是对象 instanceof toString constructor //3 建立相应的数组或对象 function deepClone(origin,target){ var target=target || {}, toStr=Object.prototype.toString, arrStr="[object Array]"; for(var prop in origin){ if(origin.hasOwnProperty(prop)){ //判断是不是原型上的属性 if(origin[prop] !=="null" && typeof(origin[prop])=='object'){ //引用值 target[prop]=toStr.call(origin[prop])==arrStr?[]:{}; // if(toStr.call(origin[prop])==arrStr){ // target[prop]=[]; // }else{ // target[prop]={}; // } deepClone(origin[prop],target[prop]); //递归 }else{ target[prop]=origin[prop]; } } } return target; } deepClone(obj,obj1)