代码改变世界

js深度克隆对象

2018-07-06 23:54  龙恩0707  阅读(568)  评论(0编辑  收藏  举报

js深度克隆对象

js深度克隆对象简单的记录一下,如下代码:

var obj = {
  typeOf: function(obj) {
    const toString = Object.prototype.toString;
    const 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'
    };
    return map[toString.call(obj)];
  },
  deepCopy(data) {
    const t = this.typeOf(data);
    let o,
      i;
    if (t === 'array') {
      o = [];
    } else if (t === 'object') {
      o = {};
    } else {
      return data;
    }
    if (t === 'array') {
      for (let i = 0; i < data.length; i++) {
        o.push(this.deepCopy(data[i]));
      }
    } else if (t === 'object') {
      for (i in data) {
        o[i] = this.deepCopy(data[i]);
      }
    }
    return o;
  }
};