深度对象拷贝


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

posted @ 2019-01-02 12:06  栖息地  阅读(79)  评论(0编辑  收藏  举报