前端JS深拷贝三种实现方式

写了三个深拷贝,想问问大家哪个好点?

   deepClone(obj) {
       let res = obj instanceof Array ? [] : {}
       for (const [k, v] of Object.entries(obj)) {
           res[k] = (typeof v == 'object' ? this.deepClone(v) : v)
       }
       return res;
   },
   deepClone2(obj) {
       if (obj == null || typeof obj !== "object") {
           return obj;
       }
       let newObj = null;
       // 时间对象
       if (obj.constructor === Date) {
           newObj = new obj.constructor(obj)
       } else {
           newObj = obj.constructor()
       }
       for (let key in Object.getOwnPropertyDescriptors(obj)) {
           newObj[key] = this.deepClone2(obj[key])
       }
       return newObj;
   },
   deepClone3(data) {
       let type = this.getObjType(data);
       let obj;
       if (type === 'array') {
           obj = [];
       } else if (type === 'object') {
           obj = {}
       } else {
           return data;
       }
       if (type === 'array') {
           for (let i = 0, len = data.length; i < len; i++) {
               obj.push(this.deepClone3(data[i]))
           }
       } else if (type === "object") {
           for (let key in data) {
               obj[key] = this.deepClone3(data[key])
           }
       }
       return obj;

   },
   getObjType: obj => {
       let toString = Object.prototype.toString;
       let map = {
           '[object Boolean]': 'boolean',
           '[object Number]': 'number',
           '[object String]': 'string',
           '[object Function]': 'function',
           '[object Array]': 'array',
           '[object Date]': 'date',
           '[object RegExp]': 'regExp',
           '[object Undefined]': 'undefined',
           '[object Null]': 'null',
           '[object Object]': 'object'
       };
       if (obj instanceof Element) {
           return 'element';
       }
       return map[toString.call(obj)];
   }

你可能感兴趣的:(前端JS深拷贝三种实现方式)