位置:海鸟网 > IT > JavaScript >

js中比较两个对象是否相等

中比较两个对象是否相等,给Object对象开展了一个实现而已,象java一样可以只给自己想要的类重写equals方法。

view sourceprint?
01 Object.prototype.equals = function(obj){ 

02     if(this == obj)  

03         return true; 

04     if(typeof(obj)=="undefined"||obj==null||typeof(obj)!="object")  

05         return false; 

06     var length = 0; var length1=0; 

07     for(var ele in this) { 

08         length++; 

09     }                

10     for(var ele in obj) { 

11         length1++; 

12     }                

13     if(length!=length1)  

14         return false; 

15     if(obj.constructor==this.constructor){ 

16         for(var ele in this){ 

17             if(typeof(this[ele])=="object") { 

18                 if(!this[ele].equals(obj[ele])) 

19                     return false; 

20             } 

21             else if(typeof(this[ele])=="function"){ 

22                 if(!this[ele].toString().equals(obj[ele].toString()))  

23                     return false; 

24             } 

25             else if(this[ele]!=obj[ele])  

26                 return false; 

27         } 

28         return true; 

29     } 

30     return false; 

31 };
示例如下:

view sourceprint?
1 var p1 = {name:"jack",age:18};  

2 var p2 = {name:"lucy",age:10};  

3 var p3 = {name:"jack",age:18};  

4   

5   

6 console.log(p1.equals(p2));//false  

7 console.log(p1.equals(p3));//true  

8 console.log(p1.equals({name:"jack",age:18}));//true