JS对象的深拷贝
方法一:标准版
1 function deepCopy(obj) { 2 if (typeof obj !== 'object' && obj != null) return obj; 3 4 var result = Array.isArray(obj) ? [] : {}; 5 for (var key in obj) { 6 if (obj.hasOwnProperty(key)) { 7 if (typeof obj[key] === 'object' && obj[key] !== null) { 8 result[key] = deepCopy(obj[key]); //递归复制 9 } else { 10 result[key] = obj[key]; 11 } 12 } 13 } 14 return result; 15 }
方法二:大同小异,精简版
Object.prototype.clone = function () { var o = this.constructor === Array ? [] : {}; for (var e in this) { o[e] = typeof this[e] === "object" ? this[e].clone() : this[e]; } return o; }