JavaScript中判斷變數是數組、函數或是物件類型的方法,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中複雜類型是對象,函數也是對象。對上述2者使用typeof,可以分別得到'object'和'function'。另外,還要排除null值的情況,因為typeof null 得到的也是 'object'。
複製代碼 代碼如下:
var isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
}
以上就是本文全部內容了,希望大家能夠喜歡。