Javascript - deepEqual Comparison

后端 未结 8 1289
囚心锁ツ
囚心锁ツ 2020-12-05 05:21

Question (From Eloquent Javascript 2nd Edition, Chapter 4, Exercise 4):

Write a function, deepEqual, that takes two values and returns true only if th

8条回答
  •  隐瞒了意图╮
    2020-12-05 05:47

    As you suspect, you're returning the match of the first property seen. You should return false if that property doesn't match, but keep looking otherwise.

    Also, return false if there's no prop property found on y (that is, the counts match, but not the actual properties).

    If all properties have matched, return true:

    var deepEqual = function (x, y) {
      if (x === y) {
        return true;
      }
      else if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {
        if (Object.keys(x).length != Object.keys(y).length)
          return false;
    
        for (var prop in x) {
          if (y.hasOwnProperty(prop))
          {  
            if (! deepEqual(x[prop], y[prop]))
              return false;
          }
          else
            return false;
        }
    
        return true;
      }
      else 
        return false;
    }
    

    var deepEqual = function (x, y) {
      if (x === y) {
        return true;
      }
      else if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {
        if (Object.keys(x).length != Object.keys(y).length)
          return false;
    
        for (var prop in x) {
          if (y.hasOwnProperty(prop))
          {  
            if (! deepEqual(x[prop], y[prop]))
              return false;
          }
          else
            return false;
        }
    
        return true;
      }
      else 
        return false;
    }
    
    var obj = {here: {is: "an", other: "3"}, object: 2};
    console.log(deepEqual(obj, obj));
    // → true
    console.log(deepEqual(obj, {here: 1, object: 2}));
    // → false
    console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
    // → false
    console.log(deepEqual(obj, {here: {is: "an", other: "2"}, object: 2}));
    // → false
    console.log(deepEqual(obj, {here: {is: "an", other: "3"}, object: 2}));
    // → true

提交回复
热议问题