首先說明下: 數組、函數、類數組對象 都是對象的一種。詳情可見下圖:JavaScript 數據類型javascript
一、判斷對象類型:內置對象(數組、函數、日期、正則表達式、錯誤 )、宿主對象(表示網頁結構的HTMLElement對象)、自定義對象html
/** * [_isTypeOf description] * @param {[object]} _data [對象] * @param {[string]} _type [對象類型] *內置對象:array,function,date,regexp,error *宿主對象:htmlelement(htmldivelement,htmlbodyelement...),htmlcollection *自定義對象:object * @return {Boolean} [true/false] */ var _isTypeOf = function(_data,_type){ try{ _type = _type.toLowerCase(); if (_data===null) return _type=='null'; if (_data===undefined) return _type=='undefined'; return Object.prototype.toString.call(_data).toLowerCase()=='[object '+_type+']'; }catch(e){ return !1; } }; /* examples */ var sf=[1,2,3]; // 數組 var func1 = function(){console.log(123);}; //函數 var data= new Date(); //日期 var ng= /java/g; //正則表達式 var err=new Error(); //錯誤 var syntaxError1=new SyntaxError(); var typeError1=new TypeError(); var uriError1=new URIError(); var main=document.getElementById("main"); //表示網頁結構的HTMLElement對象 var arrayLike1= document.getElementById("navList").getElementsByClassName("menu") var sf2={"0":"df","1":"ff",length:2}; //類數組對象 var sf3={"0":"df","1":"ff"}; //普通對象 var sf4={ff:"fs",td:"fe"}; //普通對象 _isTypeOf(sf,"array") _isTypeOf(func1,"function") _isTypeOf(data,"date") _isTypeOf(ng,"regexp") _isTypeOf(err,"error") _isTypeOf(syntaxError1,"error") _isTypeOf(typeError1,"error") _isTypeOf(uriError1,"error") _isTypeOf(main,"html(...)element") //字符串的頭是"html",尾是"element", 用正則表達式判斷下 _isTypeOf(main,"htmlcollection") _isTypeOf(sf2,"object") _isTypeOf(sf3,"object") _isTypeOf(sf4,"object") /* 以上返回所有爲true */
三、檢測 類數組對象java
類數組對象 定義 : 擁有 一個數值length屬性 和 對應非負整數屬性 的對象 看做是類數組對象。正則表達式
function isArrayLike(o){ var _isTypeOf = function(_data,_type){ try{ _type = _type.toLowerCase(); if (_data===null) return _type=='null'; if (_data===undefined) return _type=='undefined'; return Object.prototype.toString.call(_data).toLowerCase()=='[object '+_type+']'; }catch(e){ return !1; } }; if( o && !_isTypeOf(o,"array") && typeof o === "object" && isFinite(o.length) && o.length >= 0 && o.length === Math.floor(o.length) && o.length < 4294967296 ) return true; else return false; }