zoukankan      html  css  js  c++  java
  • 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));
  • 相关阅读:
    第七章
    第五章
    第六章
    Git使用入门
    源代码的下载和编译
    向中国最牛的前端群-鬼群致敬
    Normalize.css做了哪些事情--看代码
    谷歌浏览器:书签被误删了怎么办
    2013/8月读书计划
    Limu:JavaScript的那些书
  • 原文地址:https://www.cnblogs.com/juewuzhe/p/9870455.html
Copyright © 2011-2022 走看看