Deepcopy in Javascript


	Deepcopy in Javascript
[编程语言教程]

  1. 递归:
    没问题
function deepClone(obj) {
    var target = {};
    for(var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {   // 如果obj有key这个属性的话
            if (typeof obj[key] === ‘object‘) {
                target[key] = deepClone(obj[key]); 
            } else {
                target[key] = obj[key];
            }
        }
    }
    return target;
}

2.Json

JSON.parse(JSON.stringify(obj))

注意: 无法实现对象中方法的深拷贝

3.Object.assign()
通过Object.assign(destination, [src1, src2, ...])拷贝
可以合并多个对象的属性。
注意: 当对象只有一级属性为深拷贝;
当对象中有多级属性时,二级属性后就是浅拷贝

4.Object.create()

function deepCopy(obj) {
  var copy = Object.create(Object.getPrototypeOf(obj));
  var propNames = Object.getOwnPropertyNames(obj);
  
  propNames.forEach(function(name) {
    var desc = Object.getOwnPropertyDescriptor(obj, name);
    Object.defineProperty(copy, name, desc);
  });
  
  return copy;
}

var obj1 = { a: 1, b: {bc: 50, dc: 100, be: {bea: 1}} };
var obj2 = deepCopy(obj1);
console.log(obj2)
obj1.a = 20;
console.log(obj1)
console.log(obj2)
//Object {a: 1, b: Object}
//Object {a: 20, b: Object}
//Object {a: 1, b: Object}

改变了对象的结构。同时对引用类型也是浅拷贝,只复制一层
5.lodash._deepcopy()

Deepcopy in Javascript

原文地址:https://www.cnblogs.com/Nullc/p/14473455.html