- typeof
可以判斷數(shù)據(jù)類型,它返回表示數(shù)據(jù)類型的字符串(返回結(jié)果只能包括number,boolean,string,function,object,undefined);
可以使用typeof判斷變量是否存在(如if(typeof a!="undefined"){...});
Typeof 運(yùn)算符的問題是無論引用的對(duì)象是什么類型 它都返回object
typeof {} // object
typeof [1,2] // object
typeof /\s/ //object
//typeof用于判斷變量的基本類型,而instanceof用于判斷變量是否屬于某個(gè)對(duì)象的實(shí)例。需要注意的是,typeof對(duì)于null類型的變量會(huì)返回"object",這是一個(gè)歷史遺留問題
2.instanceof
原理 因?yàn)锳 instanceof B 可以判斷A是不是B的實(shí)例,返回一個(gè)布爾值,由構(gòu)造類型判斷出數(shù)據(jù)類型
console.log(arr instanceof Array ); // true
console.log(date instanceof Date ); // true
console.log(fn instanceof Function ); // true
//注意: instanceof 后面一定要是對(duì)象類型,大小寫不能寫錯(cuò),該方法試用一些條件選擇或分支
3.通過Object下的toString.call()方法來判斷
Object.prototype.toString.call();
console.log(toString.call(123)); //[object Number]
console.log(toString.call('123')); //[object String]
console.log(toString.call(undefined)); //[object Undefined]
console.log(toString.call(true)); //[object Boolean]
console.log(toString.call({})); //[object Object]
console.log(toString.call([])); //[object Array]
console.log(toString.call(function(){})); //[object Function]
4.根據(jù)對(duì)象的contructor判斷
console.log('數(shù)據(jù)類型判斷' - constructor);
console.log(arr.constructor === Array); //true
console.log(date.constructor === Date); //true
console.log(fn.constructor === Function); //true
5.jq中判斷數(shù)據(jù)類型的方法
jQuery提供了一系列工具方法,用來判斷數(shù)據(jù)類型,以彌補(bǔ)JavaScript原生的typeof運(yùn)算符的不足。以下方法對(duì)參數(shù)進(jìn)行判斷,返回一個(gè)布爾值。
jQuery.isArray();是否為數(shù)組
jQuery.isEmptyObject();是否為空對(duì)象 (不含可枚舉屬性)。
jQuery.isFunction():是否為函數(shù)
jQuery.isNumberic():是否為數(shù)字
jQuery.isPlainObject():是否為使用“{}”或“new Object”生成對(duì)象,而不是瀏覽器原生提供的對(duì)象。
jQuery.isWindow(): 是否為window對(duì)象;
jQuery.isXMLDoc(): 判斷一個(gè)DOM節(jié)點(diǎn)是否處于XML文檔中。