码迷,mamicode.com
首页 > Web开发 > 详细

js深度克隆对象

时间:2018-07-07 01:06:59      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:copy   regex   define   cti   size   str   add   简单的   div   

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;
  }
};

js深度克隆对象

标签:copy   regex   define   cti   size   str   add   简单的   div   

原文地址:https://www.cnblogs.com/tugenhua0707/p/9275965.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!