在 JavaScript 中,嚴格說所有資料型別都是物件,但實務上我們仍需要區分「陣列」與「普通物件」。問題是 typeof 對兩者都回傳 "object",完全幫不上忙:
var o = { 'name':'lee' };
var a = ['reg','blue'];
document.write(' o typeof is ' + typeof o);
document.write('<br />');
document.write(' a typeof is ' + typeof a);
// 輸出:
// o typeof is object
// a typeof is object
因此我們需要另外的判斷方法。
陣列有 length 屬性且為數字,普通物件沒有,於是:
var o = { 'name':'lee' };
var a = ['reg','blue'];
var getDataType = function(o){
if(typeof o == 'object'){
if(typeof o.length == 'number'){
return 'Array';
}else{
return 'Object';
}
}else{
return 'param is no object type';
}
};
alert(getDataType(o)); // Object
alert(getDataType(a)); // Array
alert(getDataType(1)); // param is no object type
alert(getDataType(true)); // param is no object type
alert(getDataType('a')); // param is no object type
這個寫法有個明顯破綻:「有 length 的類陣列物件」會被誤判成陣列,例如函式的 arguments、jQuery 物件、NodeList,還有 {length: 3} 這種普通物件。
alert(a instanceof Array); // true alert(o instanceof Array); // false
也可以判斷是否為 Object:
alert(a instanceof Object); // true alert(o instanceof Object); // true
由於陣列也屬於 Object,兩者都會是 true。因此用 instanceof 判斷時,必須先判斷 Array、最後才判斷 Object:
var getDataType = function(o){
if(o instanceof Array){
return 'Array';
}else if(o instanceof Object){
return 'Object';
}else{
return 'param is no object type';
}
};
若不照這個順序寫,把 Object 放前面:
var getDataType = function(o){
if(o instanceof Object){
return 'Object';
}else if(o instanceof Array){
return 'Array';
}else{
return 'param is no object type';
}
};
alert(getDataType(a)); // 結果變成 Object
陣列就會被誤判為 Object。
instanceof 有個缺點:它會沿原型鏈查找,因此跨 iframe 建立的陣列會判斷失敗(不同 window 的 Array 建構子不是同一個)。真正穩定的做法是:
var getDataType = function(o){
return Object.prototype.toString.call(o).slice(8, -1);
};
getDataType([]); // "Array"
getDataType({}); // "Object"
getDataType(new Date()); // "Date"
getDataType(/re/); // "RegExp"
getDataType(null); // "Null"
getDataType(undefined); // "Undefined"
而 ES5 之後已有現成方法 Array.isArray(),它正確處理了跨 iframe 的情況,是目前判斷陣列的標準答案:
if (Array.isArray(a)) { /* 是陣列 */ }
這也是本文一開始那個 slice(8, -1) 寫法的來源——它在 Array.isArray 普及之前,是各函式庫判斷陣列的共通手法。