对象深拷贝算法实现
function deepClone(obj){ /**判断非对象或者空直接返回*/ if(!obj || typeof obj !=='object'){ return obj; } /**是对象,递归调用*/ var result=Object.prototype.toString.call(obj)==='[object Array]'?[]:{}; for(var key in obj){ if(obj.hasOwnProperty(obj[key])){ result[key]=typeof obj[key] === 'object'?deepClone(obj[key]):obj[key]; } } return result; } 可以简化: function deepClone(obj){ /**是对象,递归调用*/ var result=Object.prototype.toString.call(obj)==='[object Array]'?[]:{}; for(var key in obj){ if(obj.hasOwnProperty(obj[key])){ result[key]=typeof obj[key] === 'object'?deepClone(obj[key]):obj[key]; } } return result; }
2.jQuery中$.extend()使用方法
/**将对象src1,src2合并到{}中,并且返回**/ //第一个参数为false或者不写,表示浅合并 $.extend({},src1,src2) var result=$.extend( false, {}, { name: "John", location:{city: "Boston",county:"USA"} }, { last: "Resig", location: {state: "MA",county:"China"} } result={name:"John",last:"Resig",location:{state:"MA",county:"China"} } //第一个参数为true,表示深合并 ); $.extend(true,{},src1,src2) var result=$.extend( true, {}, { name: "John", location: {city: "Boston",county:"USA"} }, { last: "Resig", location: {state: "MA",county:"China"} } ); result={name:"John",last:"Resig",location:{city:"Boston",state:"MA",county:"China"} } //当src只有一个,等同于对象的深复制 $.extend({},src)3.angular.extends()用法与jquery.extend()相似,但是是非递归的,仅仅是浅合并