JS函数"Deep comparison"。对象比较

JS function "Deep comparison". Object comparison

我想实现 JS 功能 "Deep comparison" 并遇到一个有趣的功能。

第一个案例 -

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] !!!
}

但是请看第二种情况。

第二种情况 -

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] !!!
}

在第一种情况下 Object { is: "an" } from arrValuesObjA[0] 不等于 Object { is: "an" } from arrValuesObjB[0] 但在第二种情况下它们是等于。

谁能解释一下这是怎么回事? 我认为它在某种程度上与按值复制和按引用复制有关,但我不确定。

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]]);
}

仔细看上面两种情况你都在使用objA.