深度对象拷贝

javascript

浏览数:217

2019-1-8

AD:资源代下载服务


JavaScript

function deep(obj) {
    var objStack = [];

    var isPlainObject = function (o) {
        return Object.prototype.toString.call(o) === '[object Object]';
    };

    var isArray = function (o) {
        return Object.prototype.toString.call(o) === '[object Array]';
    };

    var isError = function (o) {
        return o instanceof Error;
    };

    function _deepClone(obj) {
        var newObj, cloneObj;
        if (isArray(obj) || isPlainObject(obj)) {
            // 对象重复引用
            if (objStack.indexOf(obj) === -1) {
                objStack.push(obj);
            } else {
                return new Error('parameter Error. it is exits loop reference');
            }
        }
        if (isArray(obj)) {
            newObj = [];
            for (var i = 0, len = obj.length; i < len; i++) {
                cloneObj = _deepClone(obj[i]);
                if (!isError(cloneObj)) {
                    newObj.push(cloneObj);
                }
            }
        } else if (isPlainObject(obj)) {
            newObj = {};
            for (var key in obj) {
                cloneObj = _deepClone(obj[key]);
                if (!isError(cloneObj)) {
                    newObj[key] = cloneObj;
                }
            }
        } else {
            newObj = obj;
        }
        return newObj;
    }
    return _deepClone(obj);
}