对象深拷贝deepCopy
作者:互联网
function type(obj){ return Object.prototype.toString.call(obj).slice(8,-1); } function deepCopy(target,cloneObj){ var copy; for(var i in cloneObj){ copy = cloneObj[i];//1、i:a copy:{c:'c'} //3、i:c 'c' if(target === copy){//防止无限引用 continue; } if(type(copy) === "Array"){ //target[i] || [] 如果同名的有则在同名下进行添加,如果没有则变为[] target[i] = arguments.callee(target[i] || [],copy); }else if(type(copy) === "Object"){ //2、target[i]:{ d:'d' } ( { d:'d' }, {c:'c'} )递归 target[i] = arguments.callee(target[i] || {},copy); }else{ target[i] = copy; //4、{ d:'d' }[c] = 'c';即{ d:'d',c:'c' } } } return target; } var a = { a:{ c:"c" }, b:"b" } var obj1 = { a:{ d:'d' } } var t = deepCopy( obj1, a ); console.log( t );
标签:target,对象,cloneObj,var,deepCopy,拷贝,copy,type 来源: https://www.cnblogs.com/jokes/p/12372196.html