对象深拷贝deepCopy
function type(obj){ return Object.prototype.toString.call(obj).slice(8,-1); } function deepCopy(target,cloneObj){ var copy; for(var i in cloneObj){ //1、i: a
//8、i:undefined结束循环 copy = cloneObj[i];//2、i:a copy:{c:'c'} //4、i:c 'c' if(target === copy){//防止无限引用 continue; } if(type(copy) === "Array"){ //target[i] || [] 如果同名的有则在同名下进行添加,如果没有则变为[]
//target[i]||[] 如果有同名的对象就传进去,没有就传入空对象
//并进行递归操作,target[i]等待返回的结果
target[i] = arguments.callee(target[i] || [],copy); }else if(type(copy) === "Object"){ //3、target[i]:{ d:'d' } ( { d:'d' }, {c:'c'} )递归
//6、targte[a]= {d:'d',c:'c'} target[i] = arguments.callee(target[i] || {},copy); }else{ target[i] = copy; //5、{ d:'d' }[c] = 'c';即{ d:'d',c:'c' } } } return target;//9、返回结果 } var a = { a:{ c:"c" }, b:"b" } var obj1 = { a:{ d:'d' } } var t = deepCopy( obj1, a ); console.log( t );