在 JavaScript 中準確判斷一個變數的型別,是日常開發常遇到的課題,以下分別說明陣列、函式與物件的判斷方式。
陣列
ECMAScript5 提供了原生的 Array.isArray 來判斷陣列,IE9 及以上支援。若考慮舊瀏覽器的相容性,可用 Object.prototype.toString.call(obj) === '[object Array]' 替代。
代碼如下:
var isArray = Array.isArray || function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
函式
最簡單且效能最好的方式是 typeof obj == 'function'。但考慮到某些舊版瀏覽器存在的 bug,最可靠的方式是 Object.prototype.toString.call(obj) === '[object Function]'。
代碼如下:
var isFunction = function(obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
}
if(typeof /./ != 'function' && typeof Int8Array != 'object') {
isFunction = function(obj) {
return typeof obj == 'function';
}
}
物件
在 JavaScript 中,複雜型別是物件,函式也是物件。對兩者使用 typeof 分別會得到 'object' 與 'function'。此外還要排除 null,因為 typeof null 同樣回傳 'object'。
代碼如下:
var isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
}
以上就是本文的全部內容,希望對大家在型別判斷上有所幫助。