极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

# 如何实现一个深拷贝 (cloneDeep)

更多描述

const obj = {
  re: /hello/,
  f() {},
  date: new Date(),
  map: new Map(),
  list: [1, 2, 3],
  a: 3,
  b: 4,
};

cloneDeep(obj);

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 203 (opens new window)

const oldJson = { a: 1 };
const newJson = JSON.parse(JSON.stringify(oldJson));
oldJson.a = 2;
console.log(oldJson); // {a: 2}
console.log(newJson); // {a: 1}

Author

回答者: miaooow (opens new window)

function getType(obj){ return Object.prototype.toString.call(obj).slice(8,-1); } function cloneDeep(obj){ let target = {}; if(getType(obj)==='Object'){ for(let key in obj){ let item = obj[key]; target[key]=cloneDeep(item); } return target; }else if(getType(obj)==='Array'){ return obj.map(item => cloneDeep(item) ) }else{ return obj; } }

var obj = {foo:function(){},bar:1,name:'cat'}

var objClone = cloneDeep(obj)

参考: clone (opens new window)

  1. 如何处理复杂对象,如 DateRegexp
  2. 如何处理循环引用

Author

回答者: haiifeng (opens new window)

const oldJson = { a: 1} const newJson = {} Object.assign(newJson, oldJson) oldJson.a = 2 console.log(oldJson) // {a: 2} console.log(newJson) // {a: 1}

对于深层的复杂类型,assign 其实是浅拷贝 image

/**
 * 深拷贝关注点:
 * 1. JavaScript内置对象的复制: Set、Map、Date、Regex等
 * 2. 循环引用问题
 * @param {*} object
 * @returns
 */
function deepClone(source, memory) {
  const isPrimitive = (value) => {
    return /Number|Boolean|String|Null|Undefined|Symbol|Function/.test(
      Object.prototype.toString.call(value)
    );
  };
  let result = null;

  memory || (memory = new WeakMap());
  // 原始数据类型及函数
  if (isPrimitive(source)) {
    console.log("current copy is primitive", source);
    result = source;
  }
  // 数组
  else if (Array.isArray(source)) {
    result = source.map((value) => deepClone(value, memory));
  }
  // 内置对象Date、Regex
  else if (Object.prototype.toString.call(source) === "[object Date]") {
    result = new Date(source);
  } else if (Object.prototype.toString.call(source) === "[object Regex]") {
    result = new RegExp(source);
  }
  // 内置对象Set、Map
  else if (Object.prototype.toString.call(source) === "[object Set]") {
    result = new Set();
    for (const value of source) {
      result.add(deepClone(value, memory));
    }
  } else if (Object.prototype.toString.call(source) === "[object Map]") {
    result = new Map();
    for (const [key, value] of source.entries()) {
      result.set(key, deepClone(value, memory));
    }
  }
  // 引用类型
  else {
    if (memory.has(source)) {
      result = memory.get(source);
    } else {
      result = Object.create(null);
      memory.set(source, result);
      Object.keys(source).forEach((key) => {
        const value = source[key];
        result[key] = deepClone(value, memory);
      });
    }
  }
  return result;
}

Author

回答者: iceycc (opens new window)

(function (done) {
  if (!done) return;
  // 如何实现一个深拷贝 (cloneDeep)
  const obj = {
    re: /hello/,
    f() {},
    date: new Date(),
    map: new Map(),
    set: new Set(),
    list: [1, 2, 3],
    a: 3,
    b: 4,
    h: {
      name: "wby",
      age: 29,
    },
    e: undefined,
    d: null,
  };
  let utils = getTypes();
  const newObj = cloneDeep(obj);
  console.log(newObj);
  console.log(obj.map === newObj.map);

  function getTypes() {
    let isTypes = {};
    function isTyping(typing) {
      return function (value) {
        return Object.prototype.toString.call(value) === `[object ${typing}]`;
      };
    }
    let types = [
      "Object",
      "Function",
      "RegExp",
      "Map",
      "Set",
      "Date",
      "Array",
      "String",
    ];
    for (let type of types) {
      isTypes[`is${type}`] = isTyping(type);
    }
    return isTypes;
  }

  function cloneDeep(obj, memory) {
    let target = Object.create(null);
    memory || (memory = new WeakMap());
    for (let key in obj) {
      let value = obj[key];
      if (typeof value !== "object" || value === null) {
        target[key] = value;
      } else {
        if (utils.isSet(value)) {
          target[key] = new Set();
          for (const v of value) {
            target[key].add(cloneDeep(v, memory));
          }
        } else if (utils.isMap(value)) {
          target[key] = new Map();
          for (const [k, v] of value.entries()) {
            target[key].set(k, cloneDeep(v, memory));
          }
        } else if (utils.isObject(value)) {
          target[key] = cloneDeep(value);
        } else {
          target[key] = new Object.prototype.constructor(value);
        }
      }
    }
    return target;
  }
})(1);
 function deepCopy(obj) {
          var result = Array.isArray(obj) ? [] : {};
          for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
              if (typeof obj[key] === 'object') {
                result[key] = deepCopy(obj[key]);   //递归复制
              } else {
                result[key] = obj[key];
              }
            }
          }
          return result;
        }

Author

回答者: jkLennon (opens new window)

const oldJson = { a: 1} const newJson = {} Object.assign(newJson, oldJson) oldJson.a = 2 console.log(oldJson) // {a: 2} console.log(newJson) // {a: 1} @kucy 对于数组等引用类型的属性值,Object.assign 还是浅拷贝

Author

回答者: mrcaidev (opens new window)

JS 有原生的深拷贝 API structuredClone:

const obj1 = { a: 1 };
const obj2 = structuredClone(obj1);

obj2.a = 2;

console.log(obj1); // { a: 1 }
console.log(obj2); // { a: 2 }

Author

回答者: QC2168 (opens new window)

// 使用array from克隆
let arr = [1, 2, 3, 4, 5, 6, [{ 1: 12, 2: 24 }]];
let arr2 = Array.from(arr);
console.log(arr === arr2);

console.log(arr); // [1,2,3,4,5,6,{"1": 0,"2": 0}]
console.log(arr2); // [1,2,3,4,5,6,{"1": 0,"2": 0}]

// 解决实现不了深拷贝
const deepClone = (arr) =>
  Array.isArray(arr) ? Array.from(arr, deepClone) : arr;
let arr3 = deepClone(arr);
console.log(arr3); // [1,2,3,4,5,6,{"1": 12, "2": 24}]

arr[6][0] = { 1: 00, 2: 00 };

Author

回答者: QC2168 (opens new window)

// 使用扩展运算符实现深,浅拷贝
let arr = [1, 2, 3, 4, 5, 6, [{ 1: 12, 2: 24 }]];
let arr2 = [...arr];
console.log(arr === arr2);
console.log(arr); // [1,2,3,4,5,6,{"1": 0,"2": 0}]
console.log(arr2); // [1,2,3,4,5,6,{"1": 0,"2": 0}]
// 深拷贝
const deepClone = (arr) =>
  arr.map((i) => (Array.isArray(i) ? deepClone(i) : i));
let arr3 = deepClone(arr);
arr[6][0] = { 1: 00, 2: 00 };
console.log(arr3); // [1,2,3,4,5,6,{"1": 12, "2": 24}]

Author

回答者: 4may-mcx (opens new window)

function deepClone(target, map = new WeakMap()) {
  if (typeof target !== "object") return target;

  if (map.has(target)) return map.get(target); // 解决循环引用问题

  const res = Array.isArray(target) ? [] : {};
  map.set(target, res);

  for (const key in target) {
    res[key] = deepClone(target[key], map);
  }
  return res;
}

// 测试
const obj = {
  foo: {
    bar: 2,
  },
  list: [1, 2, 3],
};
obj.obj = obj; // 循环引用

const obj2 = deepClone(obj);

console.log(obj, obj2);

obj.list[3] = 3333;
obj.foo.bar = 3;

console.log(obj, obj2);

Author

回答者: coderWxs (opens new window)

function deepClone(obj, map = new WeakMap()) {
    if (obj === null) return obj
    if (obj instanceof Date) return new Date(obj)
    if (obj instanceof RegExp) return new RegExp(obj)
    if (typeof obj !== 'object') return obj
    if (map.has(obj)) return map.get(obj)   //解决循环引用
    const cloneobj = new obj.constructor()  //生成obj的对应类型
    map.set(obj, cloneobj)
    Reflect.ownKeys(obj).forEach((key) => {
        cloneobj[key] = deepClone(obj[key], map)
    })
    return cloneobj
}
Last Updated: 9/27/2022, 2:39:59 PM