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

js 对象深拷贝

时间:2020-03-30 16:36:01      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:rip   fine   div   prot   data   undefined   class   for   lin   

const getObjType = function (obj){

    var toString = Object.prototype.toString;
    var 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)];
};

const deepClone = function(data) {
    var type = getObjType(data);
    var obj;
    if (type === ‘array‘) {
        obj = [];
    } else if (type === ‘object‘) {
        obj = {};
    } else {
        //不再具有下一层次
        return data;
    }
    if (type === ‘array‘) {
        for (var i = 0, len = data.length; i < len; i++) {
            obj.push(deepClone(data[i]));
        }
    } else if (type === ‘object‘) {
        for (var key in data) {
            obj[key] = deepClone(data[key]);
        }
    }
    return obj;
};
调用:
deepClone({})     //object
deepClone([])     //array

  

 

js 对象深拷贝

标签:rip   fine   div   prot   data   undefined   class   for   lin   

原文地址:https://www.cnblogs.com/wangyunhui/p/12598931.html

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