var extendDeep = function(parent,child){ var i, toStr = Object.prototype.toString, astr = ‘[object Array]‘; child = child || {}; for( i in parent){ if(parent.hasOwnProperty(i)){ if(typeof parent[i] === ‘object‘){ child[i] = toStr.call(parent[i])=== astr ? [] : {}; extendDeep(parent[i],child[i]); }else{ child[i] = parent[i]; } } } return child; }; //测试代码: var obj1 = { a : 1, b : { c : { d : 1 } } }; var obj2 = extendDeep(obj1); console.log(obj2);
一个简单的javascript深拷贝
时间: 2024-10-04 00:09:50