js判断两个对象是否相等

2019-06-05  本文已影响0人  蕉下客_661a
function diff(obj1,obj2){
            var o1 = obj1 instanceof Object;
            var o2 = obj2 instanceof Object;
            if(!o1 || !o2){/*  判断不是对象  */
                return obj1 === obj2;
            }

            if(Object.keys(obj1).length !== Object.keys(obj2).length){
                return false;
                //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如:数组返回下表:let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
            }

            for(var attr in obj1){
                var t1 = obj1[attr] instanceof Object;
                var t2 = obj2[attr] instanceof Object;
                if(t1 && t2){
                    return diff(obj1[attr],obj2[attr]);
                }else if(obj1[attr] !== obj2[attr]){
                    return false;
                }
            }
            return true;
        }
var a = {
            name :{
                sex :'men'
            }
        };
        var b = {
            name :{
                sex :'man'
            }
        };

结果:false

上一篇下一篇

猜你喜欢

热点阅读