Replication questions of JS objects (arrays)

topic description

JavaScript authoritative Guide [3.7 immutable primitive values and mutable object references] section, referring to

The comparison of
objects is not a comparison of values: even if two objects contain the same properties and the same values, they are not equal.

I think it"s okay to understand this, because it"s not in the same memory, it"s all independent of each other. Example given:

var o={x:1},p={x:1}; //
o===p //=>false:
var a=[],b=[];  //
a===b  //=>false; 

arrays are also objects and are declared separately.
but when it comes to the latter function, I"m confused:

function equalArrays(a,b){
    if(a.length!=b.length)return false;  //
    for(var i=0;i<a.length;iPP){         //
        if(a[i]!==b[i]) return false;    // 
     return true;                         //
  }
}

object equality should be a reference to the object identifier pointing to the same memory address, right?
even if you use the "=" mode to make two objects equal.
the above example only determines that the "key-value" pairs of the object are consistent, and can"t prove that an and b point to the same memory address?

Apr.29,2021

as mentioned above

two separate arrays are never equal

and the function of this function is

if we want to compare two separate objects or arrays

this comparison is not to compare whether two objects point to the same memory, but to compare whether the attributes or elements of the two objects are consistent.

in actual programming, we rarely judge whether two arrays or objects are consistent in order to determine whether they point to the same memory, but most just judge whether attributes or elements are consistent


the above example only determines that the "key-value" pairs of the object are consistent, and can't prove that an and b point to the same memory address?

Yes, this function cannot prove that an and b are the same memory address. The function of this function is simply to determine whether the elements of two arrays are equal.


as the book says, object comparisons are all referenced comparisons, and there is no doubt that they are equal if and only if they refer to the same base object, so we can use = and = to determine whether two arrays are equal, so why use this function?

the specific function of a function depends on its running environment, and the results produced by different environments of the same function may be different. Taking the equalArrays function for example, seeing its code implementation, we can roughly infer that the function is used to determine whether the values of two arrays are equal, not to determine whether they are congruent or not.

Menu