1. 程式人生 > >物件的深度克隆方法

物件的深度克隆方法

方法1:

function deepclone(obj) {
      if (typeof obj === 'object' && obj !== null) {
        if (obj instanceof Array) {
          let newArr = [];
          obj.forEach(item => {
            newArr.push(item);
          })
          return newArr;
        } else if (obj instanceof Object) {
          let newObj = {};

          for (let key in obj) {
            if (obj[key] instanceof (Object) && !obj[key] instanceof Function) {
              console.log(key);
              newObj[key] = arguments.callee(obj[key]);
            } else {
              newObj[key] = obj[key];
            }
          }
          return newObj;
        }
      } else {
        return;
      }
    }

方法2:方法1的簡化版

function deepclone2(obj) {
      if (typeof obj === 'object' && obj !== null) {
        let result = obj instanceof Array ? [] : {};
        for (let key in obj) {
          result[key] = typeof obj[key] === 'object' && !obj[key] instanceof Function ? arguments.callee(obj[key]) : obj[key];
        }
        return result;
      } else {
        return;
      }
    }

方法3:藉助Object.assign()和Object.create()

function deepclone3(obj) {
      let proto = Object.getPrototypeOf(obj);
      let result = Object.assign({}, Object.create(proto), obj);
      return result;
    }