In projects, we sometimes need to compare the reference types, such as common objects and arrays. We know that the reference types cannot be directly used or expected results can be obtained, therefore, we need to convert an iterative compare function into the original type for comparison. In the iteration, we should also note that, the element in an object or array may be any value. In addition to the original type value, object, and arrray, this value may also be a method, a DOM object, or a window object, as you may have noticed, some reference types cannot be iterated, and Branch judgment is required. The Code is as follows:
The 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; iif (! 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