function judgeType(change) { if (arguments.length == 0) { return '0';//無參數(shù)傳入 } if (change === null) { return 'null' } if (change === undefined && arguments.length > 0) { return 'undefined' } if (change instanceof Function) { return 'function' } if (change instanceof Array) { return 'arry' } if (change instanceof Number || typeof change == 'number') { return 'number' } if (change instanceof String || typeof change == 'string') { return 'string' } if (change instanceof Boolean || typeof change == 'boolean') { return 'boolean' } }ps:下面看下js 判斷各種數(shù)據(jù)類型
了解js的都知道, 有個typeof 用來判斷各種數(shù)據(jù)類型,有兩種寫法:typeof xxx ,typeof(xxx)
如下實例:
typeof 2 輸出 number typeof null 輸出 object typeof {} 輸出 object typeof [] 輸出 object typeof (function(){}) 輸出 function typeof undefined 輸出 undefined typeof '222' 輸出 string typeof true 輸出 boolean 這里面包含了js里面的五種數(shù)據(jù)類型 number string boolean undefined object和函數(shù)類型 function
看到這里你肯定會問了:我怎么去區(qū)分對象,數(shù)組和null呢?
接下來我們就用到另外一個利器:Object.prototype.toString.call
這是對象的一個原生原型擴展函數(shù),用來更精確的區(qū)分數(shù)據(jù)類型。
我們來試試這個玩兒意兒:
var gettype=Object.prototype.toString gettype.call('aaaa') 輸出 [object String] gettype.call(2222) 輸出 [object Number] gettype.call(true) 輸出 [object Boolean] gettype.call(undefined) 輸出 [object Undefined] gettype.call(null) 輸出 [object Null] gettype.call({}) 輸出 [object Object] gettype.call([]) 輸出 [object Array] gettype.call(function(){}) 輸出 [object Function]看到這里,剛才的問題我們解決了。
constructor也能判斷數(shù)據(jù)類型:
如:
''.constructor==String [].constructor==Array var obj= new Object() obj.constructor==Object
其實js 里面還有好多類型判斷 [object HTMLDivElement] div 對象 , [object HTMLBodyElement] body 對象 ,[object Document](IE)或者 [object HTMLDocument](firefox,google)
新聞熱點
疑難解答
圖片精選