JS对象数组深拷贝

发表于 2023-02-08 78 字 1 min read

出来啦?快给人家看看,喵呜~!
/**
 * @param { object } obj
 * @returns { object }
 */
const deepCopy = (obj) => {
  let target = null;
  if (typeof obj === 'object') {
    if (Array.isArray(obj)) {
      target = [];
      obj.forEach((item) => {
        target.push(deepCopy(item));
      });
    } else if (obj) {
      target = {};
      for (const [key, value] of Object.entries(obj)) {
        target[key] = deepCopy(obj[key]);
      }
    } else {
      target = obj;
    }
  } else {
    target = obj;
  }
  return target;
};