js对象比较

 1 Object.prototype.equals = function(obj) {
 2         if (this == obj)
 3             return true;
 4         if (typeof(obj) == "undefined" || obj == null || typeof(obj) != "object")
 5             return false;
 6         var length = 0;
 7         var length1 = 0;
 8         for (var ele in this) {
 9             length++;
10         }
11         for (var ele in obj) {
12             length1++;
13         }
14         if (length != length1)
15             return false;
16         if (obj.constructor == this.constructor) {
17             for (var ele in this) {
18                 if (typeof(this[ele]) == "object") {
19                     if (!this[ele].equals(obj[ele]))
20                         return false;
21                 } else if (typeof(this[ele]) == "function") {
22                     if (!this[ele].toString().equals(obj[ele].toString()))
23                         return false;
24                 } else if (this[ele] != obj[ele])
25                     return false;
26             }
27             return true;
28         }
29         return false;
30     };
31     var p1 = {
32         name: "jack",
33         age: 18
34     };
35     var p2 = {
36         name: "lucy",
37         age: 10
38     };
39     var p3 = {
40         name: "jack",
41         age: 18
42     };
43     console.log(p1.equals(p2)); //false 
44     console.log(p1.equals(p3)); //true 
45     console.log(p1.equals({
46         name: "jack",
47         age: 18
48     })); //true

 

posted @ 2014-03-25 16:08  月月光  阅读(684)  评论(0编辑  收藏  举报