一维

Object.assign()

  1. var obj = { a: {a: "hello"}, b: 33 };
  2. var newObj = Object.assign({}, obj);
  3. newObj.a.a = "hello world";
  4. console.log(obj); // { a: {a: "hello world"}, b: 33 };
  5. console.log(newObj); // { a: {a: "hello world"}, b: 33 };
  6. console.log(obj.a.a==newObj.a.a); // true
  7. console.log(obj.a.a===newObj.a.a); // true

$.extend({},obj)

  1. var obj = { a: {a: "hello"}, b: 33 };
  2. var newObj = $.extend({}, obj);
  3. newObj.a.a = "hello world";
  4. console.log(obj); // { a: {a: "hello world"}, b: 33 };
  5. console.log(newObj); // { a: {a: "hello world"}, b: 33 };
  6. console.log(obj.a.a==newObj.a.a); // true
  7. console.log(obj.a.a===newObj.a.a); // true

二维

JSON.parse(JSON.stringify(obj))

  1. var obj = { a: {a: "hello"}, b: 33 };
  2. var newObj = JSON.parse(JSON.stringify(obj));
  3. newObj.b = "hello world";
  4. console.log(obj); // { a: "hello", b: 33 };
  5. console.log(newObj); // { a: "hello world", b: 33};
  6. console.log(obj==newObj); // false
  7. console.log(obj===newObj); // false

deepClone()

  1. function deepClone(obj){
  2. if(typeof obj !== "object") return;
  3. let newObj = obj instanceof Array ? [] : {};
  4. for(let key in obj){
  5. if(obj.hasOwnProperty(key)){
  6. newObj[key] = typeof obj[key] === "object" ? deepClone(obj[key]) : obj[key];
  7. }
  8. }
  9. return newObj;
  10. }
  11. let obj = {a: 11, b: function(){}, c: {d: 22}};
  12. deepClone(obj); // {a: 11, b: f(), c: {d: 22}};

性能总结

一维数据结构的深拷贝方法建议使用:Object.assign();

二维数据结构及以上的深拷贝方法建议使用:JSON.parse(JSON.stringify());

特别复杂的数据结构的深拷贝方法建议使用:Loadsh.cloneDeep();