Javascript 判斷對象是否相等


在Javascript中相等運算包括"==","==="全等,如何判斷兩個對象是否相等?

var obj1 = {
    name: "linchu",
    age: "12"
}
 
var obj2 = {
    name: "linchu",
    age : "12"
}
 
//Outputs: false
console.log(obj1 == obj2);
 
//Outputs: false
console.log(obj1 === obj2);
function 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;
}
 
var obj1 = {
    name: "linchu",
    age: "12"
};
 
var obj2 = {
    name: "linchu",
    age: "12"
};
 
//Outputs: true
console.log(isObjectValueEqual(obj1, obj2));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM