在JavaScript

时间:2016-09-25 01:51:31

标签: javascript arrays object comparison comparison-operators

我知道有很多基于此的问题,但我正在尝试创建自己的版本。我也知道有一个lodash版本。

这是我目前的代码:

var deepEqual = function(obj1, obj2) {
  console.log(obj1, obj2);
  // if they reference the same object in memory, then they are the same
  if (obj1 === obj2) {
    return true; 
  }

  if (Array.isArray(obj1) && Array.isArray(obj2) &&
      obj1.length === obj2.length) {
    for (var i = 0; i < obj1.length; i++) {
      if (!deepEqual(obj1[i], obj2[i])) {
        return false;
      }
    }
  }

  // if they don't have the same length, then not equivalent
  if ( Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
  }

  // if they don't have the same properties, then not equivalent
  for (var key in obj1) {
    if (!(key in obj2) || !deepEqual(obj1[key], obj2[key])) { // line 24
      return false;
    }
  }

  return true;
}

当我测试时

var obj = {here: {is: "an"}, object: 2, here: "is", an: ['a','r',{r: {a:'y'}}, ['!']]}; 
console.log(deepEqual(obj, {here: {is: "an"}, object: 2, here: "is", an: ['a','r',{r: {a:'y'}}, ['!']]}));

它会返回true,但当我在'y'的第二个参数中更改'THIS_IS_NOT_y'时:我得到了

console.log(deepEqual(obj, {here: {is: "an"}, object: 2, here: "is", an: ['a','r',{r: {a:'THIS_IS_NOT_y'}}, ['!']]}))

我明白了:

TypeError: invalid 'in' operand obj2 (line 24 in function deepEqual) 

我不知道如何解决这个问题。

除了修复上述错误外,我的代码中是否还有其他类型/案例?

1 个答案:

答案 0 :(得分:0)

    function deepEqual(obj1,obj2){

      if(obj1 === obj2) {   //Same object reference
            return true; }

      if( Object.keys(obj1).length !== Object.keys(obj2).length) {
            return false; }  // If length is not same objects are not


     for(var i in obj1){
       if((obj1[i] !== null && typeof obj1[i] === 'object') && 
          (obj2[i] !== null && typeof obj2[i] === 'object')){

               return deepEqual(obj1[i],obj2[i]);}

       else if(((typeof obj1[i]) != 'object') && 
               ((typeof obj1[i]) != 'object')){
                     if(obj1[i]===obj2[i]){
                        return true; // These are identical values!
                      }
                }

       else if(obj1[i]==null && obj2[i]==null)
                { return true; } 

       else return false; //If they are not equal 
      }
   }         
    var obj = {here: {is: "an"}, object: 2, here: "is", an: ['a','r',{r: {a:'y'}}, ['!']]}; 

    console.log(deepEqual(obj, {here: {is: "an"}, object: 2, here:    "is", an: ['a','r',{r: {a:'THIS_IS_NOT_y'}}, ['!']]}));