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;
  }

 

posted @ 2019-10-17 15:11  Bruce_Grace  阅读(191)  评论(0编辑  收藏  举报