欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js判断两个对象是否相等

程序员文章站 2022-03-02 13:03:30
...

有两个对象obj1和obj2

let obj1 = {
   a = 1
}
let obj2 = {
   a = 1
}

比较obj1和obj2:

obj1 == obj2 //false
obj1 === obj2 //false

obj1和obj2不是同一个指针对象,因此不相等。
下面是比较他们的正确方法:

方法一
比较两个对象的名和键值,都相同,那么两个对象相等。

isObjectValueEqual = (a, b) => {
    // Of course, we can do it use for in 
    // Create arrays of property names
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);
    
    // If number of properties is different,
    // objects are not equivalent
    if (aProps.length != bProps.length) {
        return false;
    }
    
    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];
    
        // If values of same property are not equal,
        // objects are not equivalent
        if (a[propName] !== b[propName]) {
            return false;
        }
    }
    
    // If we made it this far, objects
    // are considered equivalent
    return true;
}

方法二
对象里包含对象或者嵌套数组时,加递归。

isObjectValueEqual = (a, b) => {
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);
    if (aProps.length != bProps.length) {
        return false;
    }
    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i]
        var propA = a[propName]
        var propB = b[propName]
        if ((typeof (propA) === 'object')) {
            if (this.isObjectValueEqual(propA, propB)) {
                return true
            } else {
                return false
            }
        } else if (propA !== propB) {
            return false
        } else { }
    }
    return true
}

方法二代码链接

https://www.jianshu.com/p/7407bd65b15d

this.isObjectValueEqual(obj1, obj2); //true