我想实现JS功能"深度比较"和一个有趣的功能相遇。
第一案 -
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] !!!
}
&#13;
第二案 -
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] !!!
}
&#13;
在第一种情况下,对象{是:&#34;&#34;来自arrValuesObjA [0]并不等于对象{是:&#34;&#34;来自arrValuesObjB [0],但在第二种情况下它们是相等的。
任何人都能解释一下发生了什么吗? 我认为它以某种方式与按值复制相关并通过引用复制,但我不确定。
答案 0 :(得分: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] ] );
}
在上述两种情况下仔细查看您使用的是objA
。