比较两个对象并没有给出正确的结果

时间:2015-12-19 03:46:07

标签: javascript

我想比较两个对象。年龄不同但仍然说它们是相同的.. 这是我的代码

var personA =
    {
        name: "Josh Kloss",
        age: 33
    }
var personmB =
{
    name: 'Josh Kloss',
    age: 43
}

function compareTwoPeople(a, b) {

    var person1 = Object.keys(a);
    var person2 = Object.keys(b);
    if (person1.length !== person2.length) {
        console.log("They are not same");
    }
    else {
        for (var i = 0; i < person1.length; i++) {
            if (person1[i] === person2[i]) {
                console.log("They are  same");
            }
        }
    }

}

compareTwoPeople(personA, personmB);

我如何比较这两个对象...... 感谢。

4 个答案:

答案 0 :(得分:0)

您正在查找person1[i] [ 'name', 'age' ][0],即'name',即密钥名称。两个对象都是一样的。您问题的快速解决方案是:

if (a[person1[i]] !== b[person2[i]]) {
    console.log("They are not the same");
    return;
}

然而,这不是一个很好的平等测试,因为你的对象可以有两个键,但键不同。

答案 1 :(得分:0)

关闭,只需要稍微整理一下比较,就可以使用键和迭代器来获取对象值。

var personA =
    {
        name: "Josh Kloss",
        age: 33
    };
var personB =
{
    name: 'Josh Kloss',
    age: 43
};

function compare(a, b) {
  var aKeys = Object.keys(a),
      bKeys = Object.keys(b);

  if(aKeys.length != bKeys.length) return false;

  for(var i = 0; i < aKeys.length; i++) {
    if(a[aKeys[i]] != b[bKeys[i]]) return false;
  }

  return true;

}

compare(personA, personB);

答案 2 :(得分:0)

您可以考虑将Array.prototype.every用于属性值比较部分。它是有效的,因为它在第一次不匹配时返回false,而不是在不需要时覆盖所有属性:

var personA = {name: "Josh Kloss", age: 33};
var personB = {name: 'Josh Kloss', age: 43};

// Return true if objects a and b have the same properties
// with the same values. Otherwise, false.
function compareTwoPeople(a, b) {

  var person1 = Object.keys(a);
  var person2 = Object.keys(b);

  // Use first test to initialise result
  var result = person1.length === person2.length;

  // If passed the first test, do the second
  if (result) {

    // Use every to test each value, returns false at first mismatch
    result = person1.every(function(prop){
      return a[prop] === b[prop];
    });
  }
  return result;
}

document.write('Are they the same? ' + compareTwoPeople(personA, personB));

答案 3 :(得分:-1)

您可以通过浏览每个属性进行比较,

var personA =
    {
        name: "Josh Kloss",
        age: 33
    };

var personB =
{
    name: 'Josh Kloss',
    age: 43
};

function getObjectSize(obj){
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
}

function isObjectsEqual(a, b){

    //check objects has equal length
    if(getObjectSize(a) !== getObjectSize(b)){
        return false;
    }

    //check properties are equal
    for (var key in a) {

        if (b.hasOwnProperty(key)){

            if(a[key] != b[key]){
                return false;
            }
        }
        else{
            return false;
        }
    }

    return true;
}

isObjectsEqual(personA, personB); //test function