js判斷數(shù)據(jù)類型的五種方法

  1. 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文檔中。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容