在動手實作「深比較」時,最容易忽略的一點是:物件或陣列裡的元素並不保證只是原始型別。它可能是巢狀的物件、陣列,也可能是一個函式、一個 DOM 節點,甚至是 window 本身。更麻煩的是,並非所有引用型別都適合直接 for...in 遞迴下去——DOM 節點就是典型的例子,硬遞迴很容易踩到無解的循環或權限問題,因此必須先分流年分支。
下面的 compare 函式把這些情況都收攏在一起:先用 typeof 攔掉原始型別與 null,再比對 constructor 是否一致,接著針對 Date、Function、Array 各自處理,最後才落到一般物件的屬性枚舉比較。
程式碼如下:
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)); //為了方便,此處假定 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,'$1') === b.toString().replace(fn,'$1'); //硬編碼中聲明函數的方式會影響到 toString 的結果,因此用正則進行格式化
};
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;
}
原始型別與 null 先攔一輪。這一步順手把 NaN 當成相等處理,實務上算是一種取捨,因為 NaN !== NaN 是 JS 的常識,若不特別約定,任何含 NaN 的結構都會永遠比較失敗。
constructor 不一致直接判 false。用原型身分當作型別標籤,比一堆 instanceof 判斷來得乾脆。
函式比較用 toString。但函式的宣告方式(具名、匿名)會影響 toString 的輸出,所以用 fn 正則把函式名稱那一段剝掉再比,讓 function aaa(){alert(1)} 與 function(){alert(1)} 被視為同一份實作。
DOM 節點只比參照。default 分支裡偵測到 childNodes 或 parentNode 存在時,就退回最保守的 a === b,避免陷入節點樹的無限遞迴。
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
可以看到屬性順序不影響結果,而陣列順序會影響結果,這正是物件與陣列在語意上的差別。若要在正式專案中使用,建議再補上循環參照的偵測(例如以 WeakSet 記錄已拜訪過的節點),並把 arguments.callee 換成具名函式表達式,因為 strict mode 下 callee 是被禁止的。