Skip to content

Instantly share code, notes, and snippets.

@xydiva
Last active May 10, 2018 02:37
Show Gist options
  • Save xydiva/b535994bdd7166f9ff0f0a32d8614358 to your computer and use it in GitHub Desktop.
Save xydiva/b535994bdd7166f9ff0f0a32d8614358 to your computer and use it in GitHub Desktop.
js对象的深度克隆代码实现(考虑兼容)
// 1
function cloneObject(obj, parent) {
    if (typeof obj !== 'object') {
        return null;
    }

    const o = obj instanceof Array ? [] : {};

    for (let key in obj) {
        let item = obj[key];
        if (typeof item === 'object') {
            o[key] = cloneObject(item);
        }
        else {
            o[key] = item;
        }
    }

    return o;
}

// 2
function cloneObject(obj, parent) {
    const o = parent || {};
    for (let key in obj) {
        let item = obj[key];
        if (typeof item === 'object') {
            o[key] = Object.prototype.toString.call(item) === '[object Array]' ? [] : {};
            cloneObject(item, o[key]);
        }
        else {
            o[key] = obj[key];
        }
    }
    return o;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment