In an iteration, we should also note that an object or an element in an array may be an arbitrary value--except for the original type value, object, Arrray, which may be a method, a DOM object, or a Window object, which you may have noticed, There are partial reference types that cannot be iterated and require branch judgments, as follows:
Copy Code code as follows:
function Compare (a,b) {
Var
PT =/undefined|number|string|boolean/,
fn =/^ (function\s*) (\w*\b)/,
CR = "Constructor",
cn = "ChildNodes",
PN = "ParentNode",
CE = Arguments.callee;
if (Pt.test (typeof a) | | | pt.test (typeof b) | | a = = = NULL | | b = = NULL) {
return a = = B | | (isNaN (a) && isNaN (b)); For convenience, this assumes nan = = Nan
}
if (A[CR]!== B[CR]) {
return false;
}
Switch (A[CR]) {
Case Date: {
return a.valueof () = = = B.valueof ();
};
Case Function: {
Return a.tostring (). Replace (FN, ' $ ') = = B.tostring (). Replace (FN, ' $ '); The way a function is declared in hard coding affects the result of ToString, so it is formatted with a regular
};
Case Array: {
if (a.length!== b.length) {
return false;
}
for (Var i=0;i<a.length;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;
}
Console.log (compare ({},{a:1})); False
Console.log (compare ({a:1},{b:2})); False
Console.log (compare ({b:2,a:1},{a:1,b:2})); True
Console.log (Compare ({a:function () {return false;},b:2},{a:function () {return false;},b:2})); True
Console.log (Compare ([],[])); True
Console.log (Compare ([2,1],[1,2])); False
Console.log (Compare (function () {alert (1)},function () {})); False
Console.log (Compare (function aaa () {alert (1)},function () {alert (1)})); True
Console.log (Compare (document.getElementsByTagName ("a") [0],document.getelementsbytagname ("a") [1])); False
Console.log (Compare (document.getElementsByTagName ("a") [0],document.getelementsbytagname ("a") [0])); True