Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第392天 如何判断两个对象相等? #2365

Open
haizhilin2013 opened this issue May 11, 2020 · 3 comments
Open

[js] 第392天 如何判断两个对象相等? #2365

haizhilin2013 opened this issue May 11, 2020 · 3 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第392天 如何判断两个对象相等?

我也要出题

@haizhilin2013 haizhilin2013 added the js JavaScript label May 11, 2020
@jsThin
Copy link

jsThin commented May 20, 2020

JSON.stringify(obj)==JSON.stringify(obj)

@bozaigao
Copy link

bozaigao commented Sep 22, 2020

提供另一种写法:

function isSameObject(object1, object2) {
    if (Object.prototype.toString.call(object1) === '[object Object]' &&
        Object.prototype.toString.call(object2) === '[object Object]') {
        if (Object.keys(object1).length !== Object.keys(object2).length) {
            return false;
        }
        for (let key in object1) {
            if (!object2[key] || object1[key] !== object2[key]) {
                return false;
            }
        }
    }
    return true;
}

当然JSON.stringify(obj)==JSON.stringify(obj)执行速度是最快的

@hyj443
Copy link

hyj443 commented Oct 23, 2021

写了一个可以判断嵌套对象的

function equals(a, b) {
    
    const tostring = Object.prototype.toString;
    const objType = '[object Object]';

    if (tostring.call(a) !== objType || tostring.call(a) !== objType) {
        return false;
    }

    const lenA = Object.keys(a).length;
    const lenB = Object.keys(b).length;

    if (lenA !== lenB) {
        return false;
    }

    for (const key in a) {
        if (a.hasOwnProperty(key) && !b.hasOwnProperty(key)
            || !a.hasOwnProperty(key) && b.hasOwnProperty(key)
        ) {
            return false;
        }
        if (tostring.call(a[key]) === objType) {
            if (!equals(a[key], b[key])) {
                return false;
            }
        } else {
            if (a[key] !== b[key]) {
                return false;
            }
        }
    }
    return true;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

4 participants