在JavaScript中比较对象的最佳方法是什么?

例子:

var user1 = {name : "nerd", org: "dev"};
var user2 = {name : "nerd", org: "dev"};
var eq = user1 == user2;
alert(eq); // gives false

我知道如果两个对象引用完全相同的对象,那么它们是相等的,但是有没有方法检查它们是否具有相同的属性值?

以下方式对我有效,但这是唯一的可能性吗?

var eq = Object.toJSON(user1) == Object.toJSON(user2);
alert(eq); // gives true

当前回答

以下是我的ES3注释解决方案(代码后的血腥细节):

function object_equals( x, y ) {
  if ( x === y ) return true;
    // if both x and y are null or undefined and exactly the same

  if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
    // if they are not strictly equal, they both need to be Objects

  if ( x.constructor !== y.constructor ) return false;
    // they must have the exact same prototype chain, the closest we can do is
    // test there constructor.

  for ( var p in x ) {
    if ( ! x.hasOwnProperty( p ) ) continue;
      // other properties were tested using x.constructor === y.constructor

    if ( ! y.hasOwnProperty( p ) ) return false;
      // allows to compare x[ p ] and y[ p ] when set to undefined

    if ( x[ p ] === y[ p ] ) continue;
      // if they have the same strict value or identity then they are equal

    if ( typeof( x[ p ] ) !== "object" ) return false;
      // Numbers, Strings, Functions, Booleans must be strictly equal

    if ( ! object_equals( x[ p ],  y[ p ] ) ) return false;
      // Objects and Arrays must be tested recursively
  }

  for ( p in y )
    if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) )
      return false;
        // allows x[ p ] to be set to undefined

  return true;
}

在开发这个解决方案的过程中,我特别关注了角落的情况,效率,但试图产生一个简单的解决方案,希望能有一些优雅。JavaScript允许空的和未定义的财产,对象具有原型链,如果不进行检查,可能会导致非常不同的行为。

首先,我选择不扩展Object.prototype,主要是因为null不能作为比较对象之一,并且我认为null应该是一个有效的对象,可以与其他对象进行比较。其他人也注意到了Object.prototype的扩展对其他代码可能产生的副作用。

必须特别注意处理JavaScript允许对象财产设置为未定义的可能性,即存在值设置为未确定的财产。上述解决方案验证了这两个对象是否具有相同的设置为未定义的财产以报告相等性。这只能通过使用Object.hasOwnProperty(property_name)检查财产是否存在来完成。还要注意,JSON.stringify()删除了设置为未定义的财产,因此使用此表单进行比较时将忽略设置为未确定值的财产。

只有当函数共享相同的引用,而不仅仅是相同的代码时,才应该认为它们是相等的,因为这不会考虑这些函数原型。因此,比较代码字符串不能保证它们具有相同的原型对象。

这两个对象应该具有相同的原型链,而不仅仅是相同的财产。这只能通过比较两个对象的构造函数以确保严格相等来跨浏览器测试。ECMAScript 5将允许使用Object.getPrototypeOf()测试他们的实际原型。一些web浏览器还提供了__proto__属性,该属性可以执行相同的操作。对上述代码的一个可能的改进将允许在任何可用的情况下使用这些方法之一。

这里使用严格比较是最重要的,因为2不应被视为等于“2.0000”,false也不应被认为等于null、undefined或0。

出于效率考虑,我会尽快比较财产的相等性。然后,只有在这失败的情况下,才能查找这些财产的类型。速度提升对于具有大量标量财产的大型对象来说意义重大。

不再需要两个循环,第一个循环从左侧对象检查财产,第二个循环从右侧检查财产并仅验证存在性(而不是值),以捕获使用未定义值定义的这些财产。

总的来说,这段代码只需要16行代码(没有注释)就可以处理大部分的角情况。


更新(2015年8月13日)。我实现了一个更好的版本,因为函数value_equals()速度更快,能够正确地处理诸如NaN和0不同于-0的拐角情况,可以选择强制对象的财产顺序并测试循环引用,作为Toubkal项目测试套件的一部分,它由100多个自动测试支持。

其他回答

不幸的是,没有完美的方法,除非您递归地使用_proto_并访问所有非枚举财产,但这只适用于Firefox。

因此,我所能做的就是猜测使用场景。


1) 快速且有限。

当您有简单的JSON样式的对象,但内部没有方法和DOM节点时,可以使用:

 JSON.stringify(obj1) === JSON.stringify(obj2) 

财产的顺序很重要,因此此方法将为以下对象返回false:

 x = {a: 1, b: 2};
 y = {b: 2, a: 1};

2) 缓慢且更通用。

在不深入原型的情况下比较对象,然后递归地比较财产的投影,还比较构造函数。

这几乎是正确的算法:

function deepCompare () {
  var i, l, leftChain, rightChain;

  function compare2Objects (x, y) {
    var p;

    // remember that NaN === NaN returns false
    // and isNaN(undefined) returns true
    if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
         return true;
    }

    // Compare primitives and functions.     
    // Check if both arguments link to the same object.
    // Especially useful on the step where we compare prototypes
    if (x === y) {
        return true;
    }

    // Works in case when functions are created in constructor.
    // Comparing dates is a common scenario. Another built-ins?
    // We can even handle functions passed across iframes
    if ((typeof x === 'function' && typeof y === 'function') ||
       (x instanceof Date && y instanceof Date) ||
       (x instanceof RegExp && y instanceof RegExp) ||
       (x instanceof String && y instanceof String) ||
       (x instanceof Number && y instanceof Number)) {
        return x.toString() === y.toString();
    }

    // At last checking prototypes as good as we can
    if (!(x instanceof Object && y instanceof Object)) {
        return false;
    }

    if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
        return false;
    }

    if (x.constructor !== y.constructor) {
        return false;
    }

    if (x.prototype !== y.prototype) {
        return false;
    }

    // Check for infinitive linking loops
    if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
         return false;
    }

    // Quick checking of one object being a subset of another.
    // todo: cache the structure of arguments[0] for performance
    for (p in y) {
        if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
            return false;
        }
        else if (typeof y[p] !== typeof x[p]) {
            return false;
        }
    }

    for (p in x) {
        if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
            return false;
        }
        else if (typeof y[p] !== typeof x[p]) {
            return false;
        }

        switch (typeof (x[p])) {
            case 'object':
            case 'function':

                leftChain.push(x);
                rightChain.push(y);

                if (!compare2Objects (x[p], y[p])) {
                    return false;
                }

                leftChain.pop();
                rightChain.pop();
                break;

            default:
                if (x[p] !== y[p]) {
                    return false;
                }
                break;
        }
    }

    return true;
  }

  if (arguments.length < 1) {
    return true; //Die silently? Don't know how to handle such case, please help...
    // throw "Need two or more arguments to compare";
  }

  for (i = 1, l = arguments.length; i < l; i++) {

      leftChain = []; //Todo: this can be cached
      rightChain = [];

      if (!compare2Objects(arguments[0], arguments[i])) {
          return false;
      }
  }

  return true;
}

已知问题(嗯,它们的优先级很低,可能你永远不会注意到它们):

具有不同原型结构但投影相同的对象函数可以具有相同的文本,但引用不同的闭包

测试:通过测试来自如何确定两个JavaScript对象的相等性?。

如果要显式检查方法,可以使用method.toSource()或method.toString()方法。

  Utils.compareObjects = function(o1, o2){
    for(var p in o1){
        if(o1.hasOwnProperty(p)){
            if(o1[p] !== o2[p]){
                return false;
            }
        }
    }
    for(var p in o2){
        if(o2.hasOwnProperty(p)){
            if(o1[p] !== o2[p]){
                return false;
            }
        }
    }
    return true;
};

比较ONE-LEVEL对象的简单方法。

如果您在没有JSON库的情况下工作,也许这将帮助您:

Object.prototype.equals = function(b) {
    var a = this;
    for(i in a) {
        if(typeof b[i] == 'undefined') {
            return false;
        }
        if(typeof b[i] == 'object') {
            if(!b[i].equals(a[i])) {
                return false;
            }
        }
        if(b[i] != a[i]) {
            return false;
        }
    }
    for(i in b) {
        if(typeof a[i] == 'undefined') {
            return false;
        }
        if(typeof a[i] == 'object') {
            if(!a[i].equals(b[i])) {
                return false;
            }
        }
        if(a[i] != b[i]) {
            return false;
        }
    }
    return true;
}

var a = {foo:'bar', bar: {blub:'bla'}};
var b = {foo:'bar', bar: {blub:'blob'}};
alert(a.equals(b)); // alert's a false

我修改了上面的代码。对于我0!==false和null!==未定义。如果不需要这样严格的检查,请在代码中删除一个“=”sign-in“this[p]!==x[p]”。

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

然后我用下一个对象测试了它:

var a = {a: 'text', b:[0,1]};
var b = {a: 'text', b:[0,1]};
var c = {a: 'text', b: 0};
var d = {a: 'text', b: false};
var e = {a: 'text', b:[1,0]};
var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
var i = {
    a: 'text',
    c: {
        b: [1, 0],
        f: function(){
            this.a = this.b;
        }
    }
};
var j = {
    a: 'text',
    c: {
        b: [1, 0],
        f: function(){
            this.a = this.b;
        }
    }
};
var k = {a: 'text', b: null};
var l = {a: 'text', b: undefined};

a==b预期为真;返回true

a==c预期为假;返回false

c==d预期为假;返回false

a==e预期为假;返回false

f==g预期为真;返回true

h==g预期为假;返回false

i==j预期为真;返回true

d==k预期为假;返回false

k==l预期为假;返回false