JSON clone 实现

// 1:1克隆 (只考虑 f,s 为同一类型)
function deepCopy(s) {
    if (!Object.keys(s).length || s === null) return;
    var copy = function (f, s) {
        for (var i in s) {
            if (typeof s[i] === 'object' && !!s[i]) {
                f[i] = s[i].constructor === Array ? [] : {};
                copy(f[i], s[i]);
            }
            else {
                f[i] = s[i];
            }
        }
        return f;
    };
    return s.constructor === Array ? copy([], s) : copy({}, s);
}
// 在A的基础上,累加克隆B (只考虑 f,s 为同一类型)
function deepCopy(f, s) {
    if (!Object.keys(s).length || f === null) return;
    for (var i in s) {
        if (typeof s[i] === 'object' && !!s[i]) {
            f[i] = s[i].constructor === Array ? [] : {};
            deepCopy(f[i], s[i]);
        }
        else {
            f[i] = s[i];
        }
    }
    return f;
}

 

posted @ 2016-06-20 23:04  koala_熊  Views(758)  Comments(0Edit  收藏  举报