Javascript Deep Comparison

后端 未结 3 442
感动是毒
感动是毒 2021-01-21 05:35

Questions about deep comparison of objects have been asked, and I have the solution. But there is a line in the solution that I don\'t completely understand.

This is the

相关标签:
3条回答
  • 2021-01-21 06:00

    According to MDN:

    The in operator returns true if the specified property is in the specified object.

    Also:

    The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

    So to answer your first question, prop in a is checking whether prop, a field from object b, exists in object a.

    To answer your second question, deepEqual(a[prop], b[prop]) is checking whether the object a[prop] and b[prop] are equal including all its children and contents.

    0 讨论(0)
  • 2021-01-21 06:01

    The in operator returns true if the object on the right of the expression contains a key with the value of the string on the left of the expression.

    Eg: prop in a is true if a contains a key with the same name as the string value of prop. Eg:

    var prop = "age";
    
    var obj1 = {
        name: "Dave",
        age: 21,
        record: { ... }
    };
    var obj2 = {
        name: "John",
        record: { ... }
    };
    
    console.log(prop in obj1); // true
    console.log(prop in obj2); // false
    

    If prop was set to "record" then deepEqual(a[prop], b[prop]) recursively compares the values in a.record and b.record.

    0 讨论(0)
  • 2021-01-21 06:11

    It's checking for existence. It says: "For each property in B, examine A. If A doesn't have the property, or if the value of the property on A doesn't deeply equal the value of the property on B, return false".

    An alternate implementation would avoid the existence check on that line, and instead use if (typeof A == 'undefined') at the top of the function to validate the input parameters at the beginning of each round of recursion...at a glance, I think that'd be equivalent, but less efficient. The current implementation avoids the invocation on the undefined property.

    0 讨论(0)
提交回复
热议问题