js实现deepCopy

1,556 阅读1分钟

function deepCopy(obj) {
    if (typeof obj === 'object') {
        var result = obj.constructor === Array ? [] : {};
        for (var i in obj) {
            result[i] = typeof obj[i] === 'object' ? deepCopy(obj[i]) : obj[i];
        }
    } else { var result = obj; }
    return result;
}

function deepClone (data) {
    const type = metaType(data);
    let obj = null;
    if (type === 'array') {
        obj = [];
        for (let i = 0; i < data.length; i++) {
            obj.push(deepClone(data[i]));
        }
    } else if (type === 'object') {
        obj = {};
        for (const key in data) {
            if (data.hasOwnProperty(key)) {
                obj[key] = deepClone(data[key]);
            }
        }
    } else {
        return data;
    }
    return obj;
}


// 匹配函数
function metaType (obj) {
    const MAP = {
        '[object String]': 'string',
        '[object Number]': 'number',
        '[object Boolean]': 'boolean',
        '[object Null]': 'null',
        '[object Undefined]': 'undefined',
        '[object Symbol]': 'symbol',
        '[object BigInt]': 'bigInt',
        '[object Object]': 'object',
        '[object Function]': 'function',
        '[object Array]': 'array',
        '[object Date]': 'date',
        '[object RegExp]': 'regExp',
        '[object Error]': 'error'
    };

    return MAP[Object.prototype.toString.call(obj)];
}