During iteration, we should also note that the elements in an object or array may be any value-except for the original type value, object, and arrray, this value may also be a method, a DOM object, or a window object. You may have noticed that some reference types cannot be iterated and need to be determined by the branch. The Code is as follows:
Copy codeThe Code is 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, it is assumed that NaN = NaN
}
If (a [cr]! = B [cr]) {
Return false;
}
Switch (a [cr]) {
Case Date :{
Return a. valueOf () === B. valueOf ();
};
Case Function :{
Return. toString (). replace (fn, '$ 1') = B. toString (). replace (fn, '$ 1'); // The method of declaring a function in hard encoding will affect the toString result. Therefore, regular expressions are used for formatting.
};
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 ){
Alen ++;
}
For (d in B ){
Blen ++;
}
If (alen! = Blen ){
Return false;
}
For (d in ){
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