2012-12-03 41 views

回答

49

可以使用=====

var thesame = obj1===obj2; 

From the MDN :

如果两个操作数都是对象,然后JavaScript的比较内部 引用时操作数指代相同的对象中 存储器中是相等的。

13

如果两个变量指向同一个对象,那么相等和严格的相等运算符会告诉你。

foo == bar 
foo === bar 
3

可能的算法:

Object.prototype.equals = function(x) 
{ 
    var p; 
    for(p in this) { 
     if(typeof(x[p])=='undefined') {return false;} 
    } 

    for(p in this) { 
     if (this[p]) { 
      switch(typeof(this[p])) { 
       case 'object': 
        if (!this[p].equals(x[p])) { return false; } break; 
       case 'function': 
        if (typeof(x[p])=='undefined' || 
         (p != 'equals' && this[p].toString() != x[p].toString())) 
         return false; 
        break; 
       default: 
        if (this[p] != x[p]) { return false; } 
      } 
     } else { 
      if (x[p]) 
       return false; 
     } 
    } 

    for(p in x) { 
     if(typeof(this[p])=='undefined') {return false;} 
    } 

    return true; 
} 
相关问题