在Javascript中比较两个对象的属性

时间:2015-11-08 05:14:37

标签: javascript object comparison deep-copy

我正在尝试学习Javascript,而我正在做的一项工作是将两个对象进行深度比较。我已经检查过以确保它们都是对象,并且我已经比较了它们各自具有的属性数量。接下来,我尝试迭代一个对象的每个属性,并将它们与所有其他对象的属性进行比较。我不确定如何获取对象属性的值并将它们与其他对象的属性进行比较,但我知道如何使用for / in循环实现属性迭代。这是我到目前为止所做的。

function deepEqual(one, two) {

//They should both be objects.
  var bool1 = (typeof one == "object" && one != null);
  var bool2 = (typeof two == "object" && two != null);
  if(bool1 != bool2) {
    return one === two;
  }

  //If they don't have the same number
  //of properies, they are not equal.
  var num1 = 0;
  var num2 = 0;
  for(oneProps in one) {
    num1++;
  }
  for(twoProps in two) {
    num2++;
  }
  if(num1 != num2) {
    return false;
  }

  //Here's where I'm stuck. I'm trying to
  //compare each of one's properties with each
  //of two's properties. If a property of one
  //doesn't match with any of two's, they are not equal.
  //I don't know how to implement this.
  for(x in one) {
    if(deepEqual(one[x], two[x]) == false) {
      return false;
    }
    else {
      continue;
    }
  }
  return true;
}

编辑:我已经改变了结尾以使用每个属性递归deepEqual,并且我得到了最大的调用堆栈大小错误。我猜错了。

0 个答案:

没有答案