检查数组内的相等对象(Javascript)

时间:2017-07-31 21:04:02

标签: javascript arrays object mocha equality

我目前正在使用Mocha运行测试,以检查数组内对象,数组和对象的相等性。我的最后一次测试目前失败,即使在我的测试的“对象”部分中,我传入了两个相似的对象并且它们通过了。

const compareObjects = function(a, b){

  for(var prop in a){
    if(a[prop] === b[prop] !== true){
      return false;
    }
  }
  return true;
}

const compareArrays = function(a, b){

  if(a.length !== b.length){
    return false;
  }

  for(var i = 0; i < a.length; i++){

    //checking for objects inside of arrays here
    if(typeof a[i] === 'object' && typeof b[i] === 'object'){
      if(compareObjects(a[i], b[i]) !== true){
        return false;
      }
    } else if (a[i] !== b[i]){
      return false;
    }
  }

  return true;
}

这失败了 -

  describe('Arrays', function() {
    it('should return false when comparing two objects inside of 
    arrays with different number of keys', function() {

      var arr1 = [
        {
          name: 'Janet',
          age: 25,
        }
      ]
      var arr2 = [
        {
          name: 'Janet',
          age: 25,
          hairColor: 'brown'
        }
      ]

      assert.equal(false, compareArrays(arr1, arr2));
    });

  });

这传递 -

  describe('Objects', function() {
    it('should return false when there is a different number of 
    keys', function() {

      var obj1 = {name: 'Janet', age: 25, hair: 'brown'}
      var obj2 = {name: 'Janet', age: 25}

      assert.equal(false, compareObjects(obj1, obj2));
    });
 }); 

1 个答案:

答案 0 :(得分:0)

作弊!使用JSON.stringify并比较字符串。

&#13;
&#13;
const a = {
  foo: "foo",
  bar: "bar",
  foobar: {
    says: "meow"
  }
};
const b = {
  foo: "foo",
  bar: "bar",
  foobar: {
    says: "meow"
  }
};
const c = {
  foo: "foo",
  bar: "baz",
  foobar: {
    says: "meow"
  }
};

const compareObjects = function(a, b) {
  for (var prop in a) {
    if (a[prop] === b[prop] !== true) {
      return false;
    }
  }
  return true;
}

const compareObjectsCheat = function(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

console.log(compareObjects(a, b));
console.log(compareObjects(a, c));

console.log(compareObjectsCheat(a, b));
console.log(compareObjectsCheat(a, c));
&#13;
&#13;
&#13;