js 对象深拷贝

Posted neo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js 对象深拷贝相关的知识,希望对你有一定的参考价值。

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 对象深拷贝的主要内容,如果未能解决你的问题,请参考以下文章

js对象深拷贝

JS中如何进行对象的深拷贝

JS深拷贝数组和对象

js的浅拷贝和深拷贝

JS基础 - 手写深拷贝

js 对象的浅拷贝和深拷贝