JS function “Deep comparison”. Object comparison

一笑奈何 提交于 2019-12-31 05:59:45

问题


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.



来源:https://stackoverflow.com/questions/48749616/js-function-deep-comparison-object-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!