JS function “Deep comparison”. Object comparison

2020-05-03 10:26发布

问题:

I wanted to implement JS function "Deep comparison" and encounter on one interesting feature.

1st case -

    var arrValuesObjA = [{ is: "an" }, 2];
    var arrValuesObjB = [{ is: "an" }, 2];

    console.log(Array.isArray(arrValuesObjA), arrValuesObjA);
    //true Array [ {…}, 2 ]   // 0: Object { is: "an" } 1: 2 length: 2
    console.log(Array.isArray(arrValuesObjB), arrValuesObjB);
    // true Array [ {…}, 2 ]  // 0: Object { is: "an" } 1: 2 length: 2


    for (let i = 0; i < arrValuesObjA.length; i++) {
        console.log(arrValuesObjA[i] === arrValuesObjB[i]);
        // First iteration - false,   second iteration - true.
        // Means Object { is: "an" } from arrValuesObjA[0] don't equal to Object { is: "an" } from arrValuesObjB[0] !!!
    }
But look into the 2nd case.

2nd case -

let objA = {here: {is: "an"}, object: 2}, objB = {here: {is: "an"}, object: 2};

    var arrKeysObjA = Object.keys(objA);
    var arrKeysObjB = Object.keys(objB);
    var arrValuesObjA = [];
    var arrValuesObjB = [];

    for (let i = 0; i < arrKeysObjA.length; i++) {
        arrValuesObjA.push( objA[ arrKeysObjA[i] ] );
    }

    for (let i = 0; i < arrKeysObjB.length; i++) {
        arrValuesObjB.push( objA[ arrKeysObjB[i] ] );
    }
    
    console.log(Array.isArray(arrValuesObjA), arrValuesObjA);
    // true Array [ {…}, 2 ]   // 0: Object { is: "an" } 1: 2 length: 2 // the same as in 1st case!
    console.log(Array.isArray(arrValuesObjB), arrValuesObjB);
    // true Array [ {…}, 2 ]   // 0: Object { is: "an" } 1: 2 length: 2 // the same as in 1st case!

    for (let i = 0; i < arrKeysObjA.length; i++) {
       console.log(arrValuesObjA[i] === arrValuesObjB[i]);
        // First iteration - true!!!,   second iteration - true.
        // Means Object { is: "an" } from arrValuesObjA[0] equal to Object { is: "an" } from arrValuesObjB[0] !!!
    }

In 1st case Object { is: "an" } from arrValuesObjA[0] don't equal to Object { is: "an" } from arrValuesObjB[0] but in the 2nd case they are equal.

Can anyone explain what's going on? I think it somehow related with copy by value and copy by reference but i'm not sure.

回答1:

   for (let i = 0; i < arrKeysObjA.length; i++) {
        arrValuesObjA.push( objA[ arrKeysObjA[i] ] );
    }

    for (let i = 0; i < arrKeysObjB.length; i++) {
        arrValuesObjB.push( objA[ arrKeysObjB[i] ] );
    }

Look carefully in both cases above you are using objA.