SoFunction
Updated on 2025-02-28

JS determines whether the reference type objects such as Object, Array, Function are equal


function compare(a,b){
var
pt = /undefined|number|string|boolean/,
fn = /^(function\s*)(\w*\b)/,
cr = "constructor",
cn = "childNodes",
pn = "parentNode",
ce = ;
if((typeof a) || (typeof b) || a === null || b === null){
return a === b || (isNaN(a) && isNaN(b)); //For convenience, it is assumed here that NaN == NaN
}
if(a[cr] !== b[cr]){
return false;
}
switch(a[cr]){
case Date : {
return () === ();
};
case Function : {
return ().replace(fn,'$1') === ().replace(fn,'$1'); //The way of declaring functions in hard code will affect the result of toString, so it is formatted with regularity
};
case Array : {
if( !== ){
return false;
}
for(var i=0;i<;i++){
if(!ce(a[i],b[i])){
return false;
}
}
break;
};
default : {
var alen = 0, blen = 0, d;
if(a === b){
return true;
}
if(a[cn] || a[pn] || b[cn] || b[pn]){
return a === b;
}
for(d in a){
alen++ ;
}
for(d in b){
blen++;
}
if(alen !== blen){
return false;
}
for(d in a){
if(!ce(a[d],b[d])){
return false;
}
}
break;
};
}
return true;
}
(compare({},{a:1})); //false
(compare({a:1},{b:2})); //false
(compare({b:2,a:1},{a:1,b:2})); //true
(compare({a:function(){return false;},b:2},{a:function(){return false;},b:2})); //true
(compare([],[])); //true
(compare([2,1],[1,2])); //false
(compare(function(){alert(1)},function(){})); //false
(compare(function aaa(){alert(1)},function(){alert(1)})); //true
(compare(("a")[0],("a")[1])); //false
(compare(("a")[0],("a")[0])); //true